无法附加分离的实体:“具有相同键的对象已经存在于ObjectStateManager” [英] Unable to attach a detached entity: "An object with the same key already exists in the ObjectStateManager"

查看:1466
本文介绍了无法附加分离的实体:“具有相同键的对象已经存在于ObjectStateManager”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图附加一个实体到ObjectContext。
当这样做时,将抛出以下InvalidOperationException:

I am trying to attach an entity to the ObjectContext. When I do so, the following InvalidOperationException is thrown:

An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same key.

我在对象状态管理器中检入并且项目不存在:

I checked in the object state manager and the item does not exist:

//Data context is actually the object context.
ObjectStateEntry contact;
while ( //Should only work once since it should be true if the item was attached
          !DataContext.ObjectStateManager.
          TryGetObjectStateEntry(Contact, out contact)
      )
      DataContext.Attach(Contact); //Here is the exception thrown.

或者看看这个抽象例子,告诉我是否有意义:

Or look at this abstract example and tell me if it makes sense:

EntityState state = Contact.EntityState; //Detached

DataContext.Attach(Contact); //Throws the exception.
DataContext.AttachTo("Entities.Contacts", Contact); //Throws the Exception

var detached = DataContext.ObjectStateManager.
                   GetObjectStateEntries(EntityState.Detached);
//InvalidArgumentException - detached entities cannot be in the obj state mgr

欢迎。

推荐答案

您的联系人实体可以有两个具有相同 EntityKey ?例如,是否可以从Contact实体获取具有相同键的两个地址实体?

Could your Contact entity have two child entities with the same EntityKey? For example, is it possible to get from the Contact entity to two Address entities with the same key?

如果指定 MergeOptions.NoTracking 上下文将乐意返回包含具有相同键的实体的分离对象图。但是,当您附加同一对象图时, System.InvalidOperationException 将被抛出。

If you specify MergeOptions.NoTracking a context will happily return a detached object graph that contains entities with the same key. However, when you attach the same object graph a System.InvalidOperationException will be thrown.

我建议你看看你附加到上下文的整个对象图,并检查是否有对象具有重复的键。

I would suggest that you look at the entire object graph that you are attaching to the context and check if there are objects with duplicate keys in it.

这篇关于无法附加分离的实体:“具有相同键的对象已经存在于ObjectStateManager”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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