我試圖將一個實體附加到ObjectContext。 當我這樣做,下面的引發InvalidOperationException:無法附加分離的實體:「ObjectStateManager中已存在具有相同鍵的對象」
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中的答案也歡迎。
我面臨着類似的問題,你能提供一個例子,你將如何看待你附加到上下文的整個對象圖,並檢查是否有對象中有重複鍵? – Eduard 2011-03-02 11:15:29