0

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 creating 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();
1
  • Show your complete editation code. This should not happend. Also what is the difference between newItem and _newItem? Commented Mar 22, 2011 at 8:59

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.