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

时间:2009-07-15 14:34:05

标签: entity-framework concurrency objectstatemanager

我正在尝试将实体附加到ObjectContext。 当我这样做时,抛出以下InvalidOperationException:

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

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

//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.

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

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

VB中的答案也很受欢迎。

4 个答案:

答案 0 :(得分:7)

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

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

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

答案 1 :(得分:5)

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

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

Dim state = a.EntityState '= Added

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

答案 2 :(得分:4)

我在申请中遇到了同样的问题。

我使用ObjectStateManager TryGetObjectStateEntry Method

解决了这个问题

实际上,EntityState属性误导了开发人员。虽然它显示Detached,但有趣的是导致错误。

答案 3 :(得分:0)

检查您是否正在设置Entity对象的EntityKey属性。如果要进行设置,请确保不要从现有实体对象进行复制。

相关问题