我有一個包含很多屬性的對象。一堆這些大對象將被插入到數據庫中,但只有一個屬性在改變。將改變的屬性不是主鍵。第一次SaveChanges成功,但隨後的失敗,「ObjectStateManager中已存在一個具有相同鍵的對象.....」。這裏是代碼的流程:EF4添加多個實體(在ObjectStateManager中已存在具有相同密鑰的對象)
//create the entity and set the properties that don't change
TheLargeObject obj = new TheLargeObject();
obj.Prop1 =
obj.Prop2 =
...
obj.Prop20 =
//create a list of values that differ between each entity
List<int> validIds = new List<int>();
private static void SaveToDatabase(TheLargeObject obj, List<int> validIds)
{
foreach (int id in validIds)
{
//this is the only property that changes
obj.KeyId = id;
//make a copy - do we really need this?
TheLargeObject newobj = new TheLargeObject();
newobj = obj;
using(Entities objContext = new Entities())
{
objContext.TheLargeObjects.AddObject(newobj); //ERROR: An object with the same key already exists in the ObjectStateManager.
objContext.SaveChanges();
}
}
}
我剛剛開始接觸EF4,所以我可能是錯誤的方式去了解這一點。 謝謝
你爲什麼不接受答案? – Sampath 2016-08-29 07:57:49