无法附加分离的实体:"ObjectStateManager中已存在具有相同密钥的对象"

Shi*_*mmy 20 concurrency entity-framework objectstatemanager

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

An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same key.
Run Code Online (Sandbox Code Playgroud)

我检查了对象状态管理器,该项目不存在:

//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.
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

VB中的答案也很受欢迎.

Dan*_*son 7

您的Contact实体是否有两个具有相同EntityKey的子实体?例如,是否可以从Contact实体获取具有相同密钥的两个Address实体?

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

我建议您查看附加到上下文的整个对象图,并检查是否存在包含重复键的对象.


Shi*_*mmy 5

答案是(我没有提到这是问题所在,因为我不知道它是这样的),如果你将导航属性设置为被跟踪实体,则会自动添加新实体:

Dim s = context.States.FirstOrDefault()
Dim a As New Address
a.State = s

Dim state = a.EntityState '= Added
Run Code Online (Sandbox Code Playgroud)

因为我不知道我一直想知道实体是如何被跟踪的.我会删除整个问题,但由于其他答案的努力可能会有所帮助,我会留在这里,投票结束,如果你认为它应该被关闭.