我正在使用Entity Framework 4.0和POCO实体,使用动态代理进行更改跟踪。我试图添加一个实体,调用SaveChanges,然后更新一些其他需要从添加的对象返回的IDENTITY值的实体。由于对象在edmx文件中不相关,因此我不能立即调用SaveChanges并让EF管理它。然后在最后我想编辑原始对象中的几个字段,然后让SaveChanges更新它。发生的事情是数据库正在为此原始项创建重复记录。它正在添加第一个对象,返回一个新ID,但是当我稍后在编辑几个字段后调用SaveChanges时,它又将该项添加到表中。有什么想法吗?
MyClass newItem = new MyClass();
newItem.field1 = 2;
newItem.field2 = false;
newItem.field3 = 44;
context.AddObject(newItem);
//force a save to get the identity of the added item so I can use it with another entity
context.SaveChanges();
//Setting the object state to unchanged (or not doing anything) will add a duplicate object
//If I set the object state to modified, it does not add a duplicate record, but it also does not save the updates
context.SetObjectState(newItem, ObjectStateEntry.Unchanged);
//do something else unrelated using the new ID returned from the IDENTITY field in the database
//update a couple of fields on the newly added item
newItem.field1 = 3;
newItem.field2 = true;
//save again
context.SaveChanges();
答案 0 :(得分:0)
我发生了类似的事情。 EF4似乎有些错误:
答案 1 :(得分:0)
在调用SetObjectState时,这是我的错误。我有一个调用此方法的包装器,并且包装器传递了错误的Enum值。现在一切正常。