我正在尝试将实体附加到 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中的答案也受到欢迎。