开发者

Entity Framework - Adding POCO with proxy object and then updating same object creates duplicate items in the database

I am using Entity Framework 4.0 with POCO entities using dynamic proxies for change tracking. I am trying to add an entity, call SaveChanges, and then update some other entities that need the IDENTITY value returned from the added object. Since the objects are not related in the edmx file, I cannot call SaveChanges at once and have EF manage it all. And then at the end I want to edit a few fields in the original object and then have SaveChanges update it. What is happening is the database is cre开发者_Go百科ating duplicate records for this original item. It is adding the first object, returning a new ID, but then when I call SaveChanges later after editing a couple of fields, it is adding the item to the table again. Any ideas?

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();


This was a mistake on my part when calling SetObjectState. I had a wrapper that called this method, and the wrapper was passing in the wrong Enum value. Everything works okay now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜