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
系統拋出錯誤,因爲它似乎試圖創建一個新的國家。
你能告訴我們Post Post和PostAddress類嗎? – 2014-09-23 12:34:25
GetCountries()是做什麼的?可能看到這個? – Thewads 2014-09-23 15:11:44
看起來像simpleRepository和allThinsEntities使用不同的DbContexts/ObjectContexts。你從一個環境中接受你的國家,並嘗試將它添加到另一個環境中。您必須首先從simpleRepsitorys上下文中分離國家,然後將其附加到allThingsEntities,然後將其分配給PostAddress.Country。 – user3411327 2014-09-23 15:55:31