我使用EF4的經驗非常有限。 我成功反序列化處於分離狀態的web服務的實體,現在我想保存到數據庫。 當使用的SaveChanges我得到以下異常:導致重複ID問題的獨立實體
System.Data.UpdateException:更新 條目中出現了錯誤。詳情請參閱內部例外。 ---> System.Data.SqlClient.SqlException:違反主鍵約束'[主鍵約束名]' '。不能在對象'[相關表名]'中插入重複的 鍵。重複的鍵值是(1)。 該聲明已被終止。
我試圖保存的實體將相關實體作爲實體集合的屬性和屬性。
來自Web服務的ID用作表的主鍵,因此不使用自動生成的ID。
下面的測試說明,我試圖解決這個問題:
[TestMethod]
public void SaveRelatedDetachedEntitiesWithoutDuplicatesTest(){
using (var db = ProductEntities()){
//testing pre-saved existing category
if (!db.CategoryGroups.Any(e => e.Id == 3)){
db.CategoryGroups.AddObject(new Database.CategoryGroupEntity(){
Id = 3,
Name = "test group 3"
});
db.SaveChanges();
}
var categoryList = new List<CategoryEntity>(){
new CategoryEntity(){
Id = 1,
Name = "test category 1",
Groups = new List<CategoryGroupEntity>(){new CategoryGroupEntity(){
Id = 1,
Name = "test group 1"
},//duplicate
new CategoryGroupEntity(){
Id = 2,
Name = "test group 2"
}
}
},
new CategoryEntity(){
Id = 2,
Name = "test category 2",
Groups = new List<CategoryGroupEntity>{
new CategoryGroupEntity(){
Id = 1,
Name = "test group 1"
},//duplicate
new CategoryGroupEntity(){
Id = 3,
Name = "test group 3"
}//already in db
}
}
};
var product = new ProductEntity(){
Categories = categoryList,
Id = 1,
Name = "test product 1",
Type = new TypeEntity { Id = 1, Name = "test type" }
};
//all above code cannot be altered as it reflects what results from the deserialization.
db.Products.AddObject(product);
//need code here to handle the duplicates
db.SaveChanges();
var test = db.Products.Where(e => e.Id == 1).FirstOrDefault();
Assert.IsNotNull(test);
Assert.IsTrue(test.Categories.Count() == 2, "missing categories from product");
Assert.IsTrue(test.Categories.ElementAt(0).Groups.Any(e => e.Id == 1), "missing group from category 1");
Assert.IsTrue(test.Categories.ElementAt(1).Groups.Any(e => e.Id == 1), "missing group from category 2");
}
}
您的幫助表示讚賞。
編輯: 我可以得到的是使用下面的代碼
var added = db.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added)
.Where(e => !e.IsRelationship).Select(e => e.Entity)
.OfType<CategoryGroupEntity>();
var duplicates = added.GroupBy(e => e.Id)
.Where(g => g.Count() > 1)
.SelectMany(g => g.Where(e => e != g.First())
事情我已經嘗試了重複,但沒有工作組的列表:
-attaching實體是重複的,以數據上下文的狀態不變。 作爲附加CategoryGroupEntity導致附加的所有相關實體重複的關鍵問題仍然
從分類收集的拆卸,實體實例,並與第一次創造了同樣的問題
結果CategoryGroupEntity實例替換他們 - 分離重複的實體實例會導致第二個類別丟失組ID 1
作爲一個方面說明,當數據庫中已存在特定的CategoryGroupEntity並嘗試保存實體時,我還需要避免重複密鑰問題使用相同的ID。
所以,我需要避免重複的關鍵問題,當具有該ID的實體存在於數據庫中或在ObjectStateManager中添加狀態時。我上面包含的測試合併了這兩種情況。
爲什麼實體框架重新插入現有的對象到我的數據庫? msdn.microsoft.com/en-us/magazine/dn166926.aspx – Colin
[如何避免重複插入在實體框架4.3.1]可能的重複(http://stackoverflow.com/questions/13285485/how-to-avoid -duplicate-insert-in-entity-framework-4-3-1) – Colin