2009-07-15 27 views
20

我試圖將一個實體附加到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中的答案也歡迎。

回答

7

您的聯繫實體是否有兩個相同的子實體EntityKey?例如,是否有可能從聯繫實體獲取具有相同密鑰的兩個地址實體?

如果指定MergeOptions.NoTracking,上下文將愉快地返回包含具有相同鍵的實體的分離對象圖。但是,當您附加同一個對象圖時,將會拋出一個System.InvalidOperationException

我建議你看看你附加到上下文的整個對象圖,並檢查是否有重複鍵的對象。

+0

我面臨着類似的問題,你能提供一個例子,你將如何看待你附加到上下文的整個對象圖,並檢查是否有對象中有重複鍵? – Eduard 2011-03-02 11:15:29

5

答案是(和我沒有提到,這是問題,因爲我不知道它是什麼),如果你設置一個導航屬性到跟蹤實體自動添加新的實體:

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

Dim state = a.EntityState '= Added 

因爲我不知道我一直在想知道如何跟蹤實體。 我會刪除整個quesion,但由於有其他答案的努力可能會有所幫助,所以我會把它留在這裏,如果您認爲它應該關閉,則投票結束。

+0

相關:http://stackoverflow.com/questions/8759699/entity-framework-creating-new-entity-with-relationship-to-existing-entity-resul – Andre 2016-05-30 13:53:41

0

檢查您是否正在設置實體對象的EntityKey屬性。如果您正在設置它,請確保您未從現有實體對象進行復制。

相關問題