20

我正在尝试将实体附加到 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

4 回答 4

7

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

如果您指定MergeOptions.NoTracking上下文将愉快地返回一个分离的对象图,其中包含具有相同键的实体。但是,当您附加相同的对象图时,将引发System.InvalidOperationException 。

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

于 2009-08-10T19:50:56.243 回答
5

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

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

Dim state = a.EntityState '= Added

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

于 2009-11-15T00:48:21.087 回答
4

我在我的应用程序中遇到了同样的问题。

我已经通过使用ObjectStateManager TryGetObjectStateEntry 方法解决了这个问题

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

于 2009-08-28T09:04:19.227 回答
0

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

于 2016-10-27T14:36:18.683 回答