[英]Adding EF object as a foreign key
好的,几天来我一直在梳头。
如何指示实体框架将对象作为现有对象的外键而不是全新对象插入? 我尝试了各种各样的事情。 我不断收到错误消息“ ObjectStateManager中已经存在具有相同键的对象。ObjectStateManager无法跟踪具有相同键的多个对象。”
我只是想在地址中添加国家/地区。 这些国家/地区都在单独的数据库表中列出。 该国家/地区来自MVC视图中发布的下拉列表,因此我只有ID。 这意味着我可以获取对象的唯一方法是查询EF,这导致对象重复。
希望有人能帮忙。 Aaarg!
中号
===更多信息===
尽管以上内容正确地指出仅设置了countryID,但这仅适用于创建方案。 它不适用于编辑。
我的控制器中有这个:
public ActionResult Edit(SiteViewModel siteViewModel)
{
if (ModelState.IsValid)
{
Site site = _unitOfWork.SiteRepository.GetById(siteViewModel.SiteID);
_unitOfWork.Detach(site);
site = Mapper.Map<SiteViewModel, Site>(siteViewModel);
site.CountryId = siteViewModel.CountryId;
...
}
}
我现在仍在使用相同的键错误获取多个对象。 如何分离国家/地区,以便可以再次将其重新添加(!),而无需将其从数据库中删除?
请帮忙!
中号
将国家/地区附加到地址的最便宜的方法是使用存根(Stub)代表您随后将国家/地区附加到地址的国家/地区。 这样可以避免在这种情况下只想附加现有国家而不进行编辑的情况下数据库的往返。
例如
// Create stub country using posted country id
var country = new Country { Id = postedId };
// Attach (NOT ADD) to context as an existing entity
// (Using Add would lead to an EntityState of Added and a violation of the
// PK unique constraint as per the question)
context.Countries.Attach(country)
// This assumes the address is attached to the context
// I.e. either its been Added to the Address DbSet
// or returned from a query on the Address DbSet
address.Country = country
context.SaveChanges();
正如Iain Galloway在评论中指出的那样,如果您的“地址->国家/地区”关系也具有外键id属性,则也可以实现以下目的:
address.CountryId = postedId;
通过SaveChanges
方法调用DetectChanges
时,Entity Framework将执行关系DetectChanges
并确保正确设置了所有导航属性。
尝试:
var id = 2; // id of item
using (var context = new Context())
{
var item = context.YourTable.Single(m => m.Id== id);
item.ForeinKey = someNewForeinKey;
context.SubmitChanges();
}
使用ForeignKey属性。 这样,您可以分配一个ID而不是拥有整个对象。 只需在您的类中包含一个int属性,并用表明int属性表示外键的属性装饰导航属性即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.