2

As explained in this topic if you like to insert or update an entity you can use the following approach:

if (myEntity.Id != 0)
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();

The problem is that in my case myEntity has some child related objects and therefore when I try to update it (myEntity.Id != 0) I receive the following exception:

System.InvalidOperationException was unhandled
Message=An object with a temporary EntityKey value cannot be attached to an object context.

If I remove the child objects (comment out) from myEntity everything works..

Does anybody know how to solve the problem? How can I update myEntity and save it with its child objects? THANKS!

EDIT:

Here the solution to the problem: stackoverflow.com/a/7969372/282649

Community
  • 1
  • 1
andrew0007
  • 1,243
  • 4
  • 18
  • 32
  • 1
    How is myEntity created? Where does that Id come from? And are the child objects new, or existing? – Gary McGill Jun 18 '14 at 21:46
  • possible duplicate of [Storing a complex detached object graph in EF6](http://stackoverflow.com/questions/21677558/storing-a-complex-detached-object-graph-in-ef6) – Gert Arnold Jun 18 '14 at 21:55
  • Hi, myEntity is already existing in the DB and loaded with EF. The Id is autoincrement and the child objects are already existing. Basically, what I want to do is simply to load my entity, change one of its property and store it back... Thanks for your feedback. – andrew0007 Jun 19 '14 at 07:04
  • 1
    Rule #1 is: make sure everything existing is attached to the context before calling `Add` of the root entity. Further: set primitive foreign key values where possible (see *foreign key associations* vs. *independent associations*). – Gert Arnold Jun 19 '14 at 07:08
  • @Gert Arnold: is it possible to solve it without external library? – andrew0007 Jun 19 '14 at 07:49
  • See my previous comment, that should do it. – Gert Arnold Jun 19 '14 at 07:55
  • Possible duplicate of [Entity 4.1 Updating an existing parent entity with new child Entities](http://stackoverflow.com/questions/7968598/entity-4-1-updating-an-existing-parent-entity-with-new-child-entities) – podiluska Feb 21 '17 at 11:27

0 Answers0