ObjectContext的对现有相关实体的实体框架6插入重复 [英] ObjectContext with Entity Framework 6 inserting duplicates on existing related entities

查看:110
本文介绍了ObjectContext的对现有相关实体的实体框架6插入重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建这有望节约几个人有些浪费时间,或者对于我来说一个星期六。

I'm creating this to hopefully save a few people some wasted hours, or in my case a Saturday.

问题如下:

我的主要实体被称为情况下,在这种情况下并在通过验证,我会保存到对象上下文,像这样

My main entity was called case in this instance and upon passing validation, I would save to the object context, like so

context.AddToCases(caseModel);
context.SaveChanges();

问题是,一个案件有一个相关的事件。我添加名为事件情境感知的项目,我是通过像这样背景下仰视

The issue was that a case had a related incident. I was adding a context aware item called incident, that I was looking up through context like so

caseModel.Incident = context.Incidents.SingleOrDefault(i => i.IncidentNumber == jumpIncidentNumber);

由于code跑了,我看得出来,model.Incident有一个的EntityKey,并添加了状态并添加重复。只是不,保存后的结论参照的是对新创建的记录。

As the code ran, I could see that model.Incident had an EntityKey and had state of Added and duplicates were being added. Not only that, the concluding reference after save was to the newly created record.

我认为我马上知道答案,我只是需要通过运行事件模型预先安装像这样

I thought that I immediately knew the answer, I simply needed to run the incident model through Attach beforehand like so

context.Attach(incident);
caseModel.Incident = incident;

错误。虽然它有不变EntityState,它仍然输入了重复。只是这一次,产生的参考值是原来的事件,不再重复。

Wrong. Although it had EntityState of unchanged, it still entered a duplicate. Except this time, the resulting reference was the original Incident, and no longer the duplicate.

推荐答案

解决方案是投进去,用的DbContext完全覆盖的ObjectContext像这样

The solution was to cast into and override ObjectContext altogether with a DBContext like so

if (model.Incident != null)
{
    DbContext dbContext = new DbContext(context, true);
    dbContext.Entry(model.Incident).State = EntityState.Unchanged;
}

尽管这起事件实体有不变的EntityState,ObjectContext的还是认出这是新的。的DbContext似乎更清楚的状态。

Despite the fact that the Incident entity had an EntityState of unchanged, ObjectContext still recognised it as new. DBContext seems much more state aware.

我希望这可以帮助别人。

I hope this helps someone.

这篇关于ObjectContext的对现有相关实体的实体框架6插入重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆