2012-03-20 60 views
1

我有一個包含其他實體列表的實體。實體列表包含主鍵(標識),外鍵和字符串。當我嘗試附加父實體時,我得到例外An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key無法附加多個實體進行插入(在ObjectStateManager中已存在具有相同密鑰的對象)

出於某種原因,實體框架(EF)認爲這是重複記錄。記錄確實具有相同的外鍵,但是作爲主鍵(int類型的Id)的屬性設置爲0,根據我的理解,這是可接受的,因爲該列是標識列。

有沒有人知道我在做什麼錯在這裏?

回答

4

如果您將附上對象與上下文相同,則不允許使用相同的主鍵值。這隻有在您添加到上下文中才有可能。

如果要插入孩子一個已經存在的父母,你可以試試下面的(例如,對於EF> = 4.1):

// put parent and all children into Added state 
context.Parents.Add(parent); 

// reset state for parent to Unchanged, but not for the children 
context.Entry(parent).State = EntityState.Unchanged; 

context.SaveChanges(); 

我假設父母和所有的孩子從上下文中分離在此代碼片段之前。

編輯

隨着ObjectContext

// put parent and all children into Added state 
objectContext.Parents.AddObject(parent); 

// reset state for parent to Unchanged, but not for the children 
objectContext.ObjectStateManager.ChangeObjectState(parent,EntityState.Unchanged); 

objectContext.SaveChanges(); 
+0

這可能與ObjectContext類? – 2012-03-20 20:03:21

+1

@ Ek0nomik:我認爲我編輯的代碼是ObjectContext的版本。 – Slauma 2012-03-20 20:11:57

相關問題