【发布时间】:2010-11-17 04:26:27
【问题描述】:
我有一个对象,上面有很多属性。一堆这些大对象将被插入到数据库中,但它们只有一个属性发生变化。将要更改的属性不是主键。第一次 SaveChanges 成功,但随后的失败并显示“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,所以我可能会以错误的方式处理这个问题。 谢谢
【问题讨论】:
-
你为什么不接受答案?