Note that there are some explanatory texts on larger screens.

plurals
  1. PONew child inserts existing parent in Entity Framework 4
    text
    copied!<p>When I try to add new child relations to an existing parent object, <em>entity tries to insert the parent object as <strong>new</strong>, instead of updating it as <strong>modified</em></strong>. I get an error saying its trying to <strong><em>insert a duplicate key</em></strong>. </p> <p>This is really stumping me, it wasn't behaving like this until I updated the model with a new relation (via update from database, not code first). Other tables in the same context, with the same many-to-many pattern <strong>do not cause this error!</strong></p> <p>I've found that if I add my child object to the context, carefully setting the ID values, not the navigation properties, it will save fine. <em>But the fix-up process isn't adding the child object to the navigation collection</em>, wich cause logic issues in other places.</p> <p>My model has a many to many relation like this:</p> <p>option -&lt; optionUnit >- Unit</p> <p>Both Option and Unit objects are <strong>existing</strong> and <strong>loaded</strong> into the context.</p> <p>Normally I would make the bridge table and set the navigation properties like below:</p> <pre><code>bridge = new OptionUnit() { OptionUnitId = Guid.NewGuid(), Unit = SelectedUnit, Option = SelectedOption, }; //Context.OptionUnits.Add(bridge); //added to context via the navigation properties </code></pre> <p>But when I do this time, entity tried to insert SelectedOption as new (even though its entity state is modifed at time of the save, not new or detached).</p> <p>To get around this I've had to make the bridge and set the id's only. I get no error on save, but its not automatically added to SelectedOption.OptionUnits via fix-up like I would expect. If i add it to the collection manually, I get the save error again.</p> <pre><code>bridge = new OptionUnit() { OptionUnitId = Guid.NewGuid(), //Unit = SelectedUnit, UnitId = SelectedUnit.UnitId, //Option = SelectedOption, OptionId = SelectedOption.OptionId, }; Context.OptionUnits.Add(bridge); </code></pre> <p>This seems to be only happening for relations on the Options Entity. The other relation, between optionUnit >- Unit has no problems and works as expected.</p> <p>It seems like theres somethign wrong with the relations, but I'm not sure where to look. I need to know whats causing this behaviour, how to fix it, and how to prevent it from happening in the future.... </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload