2014-09-23 36 views
0

我有一個項目,它的一個屬性是國家這是一個對象,我想我應該能夠執行下面的代碼。實體框架插入而不是更新

var Post = new Post(); 

country = simpleRepository.GetCountries().FirstOrDefault(c => c.CountryId == postViewModel.PostAddress.CountryId); 

post.PostAddress.Country = country; 

allThingsEntities.Posts.Add(post); 

不幸的是我得到這個錯誤,當我做:

一個實體對象不能被IEntityChangeTracker

的多個實例引用,當我改變post.PostAddress.Country = country;post.PostAddress.CountryId = country.countryId系統拋出錯誤,因爲它似乎試圖創建一個新的國家。

+0

你能告訴我們Post Post和PostAddress類嗎? – 2014-09-23 12:34:25

+0

GetCountries()是做什麼的?可能看到這個? – Thewads 2014-09-23 15:11:44

+1

看起來像simpleRepository和allThinsEntities使用不同的DbContexts/ObjectContexts。你從一個環境中接受你的國家,並嘗試將它添加到另一個環境中。您必須首先從simpleRepsitorys上下文中分離國家,然後將其附加到allThingsEntities,然後將其分配給PostAddress.Country。 – user3411327 2014-09-23 15:55:31

回答

0

這個錯誤意味着你有多個數據上下文實例。你可能會做這樣的事情,只保留一個實例。從你的Repos調用它。

public DataContext Get() 
{ 
    return _dataContext ?? (dataContext = new DataContext()); 
}