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