无法连接多个实体插入(与相同键的对象已经在ObjectStateManager存在) [英] Unable to attach multiple entities for insertion (An object with the same key already exists in the ObjectStateManager)

查看:154
本文介绍了无法连接多个实体插入(与相同键的对象已经在ObjectStateManager存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含其他实体列表的实体。实体的清单包含一个主密钥(身份),外键和一个字符串。当我尝试将父实体,我得到具有相同键的对象已经存在于ObjectStateManager例外。该ObjectStateManager不能用相同的密钥跟踪多个对象

I have an entity that contains a list of other entities. The list of entities contains a primary key (identity), foreign key and a string. When I try to attach the parent entity, I get the exception An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

由于某些原因,实体框架(EF)认为这是一个重复的记录。该记录的都具有相同的外键的,但性质是主键设置为0(类型为int的标识)的,从我的理解,是可以接受的,因为该列是标识列。

For some reason the Entity Framework (EF) thinks that this is a duplicate record. The records do have the same foreign key, but property that is the primary key (Id of type int) is set to 0 which, from my understanding, is acceptable since the column is an identity column.

有谁知道我在做什么错在这里?

Does anyone know what I'm doing wrong here?

推荐答案

同样的主键值不允许,如果你的连接的对象的背景。如果你的这是唯一可能添加他们的背景。

The same primary key values are not allowed if you attach the objects to the context. It's only possible if you add them to the context.

如果要插入孩子一个已经存在的父母,你可以试试下面的(例如,对于EF> = 4.1):

If you want to insert children for an already existing parent, you can try the following (example for EF >= 4.1):

// put parent and all children into Added state
context.Parents.Add(parent);

// reset state for parent to Unchanged, but not for the children
context.Entry(parent).State = EntityState.Unchanged;

context.SaveChanges();

我假设父母和所有的孩子都从这个code段之前的背景分离。

I am assuming that parent and all children were detached from the context before this code snippet.

修改

使用的ObjectContext

// put parent and all children into Added state
objectContext.Parents.AddObject(parent);

// reset state for parent to Unchanged, but not for the children
objectContext.ObjectStateManager.ChangeObjectState(parent,EntityState.Unchanged);

objectContext.SaveChanges();

这篇关于无法连接多个实体插入(与相同键的对象已经在ObjectStateManager存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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