My object which I am going to insert has a parent object as a navigational property.
When I “add” the object to insert it, it also set the ObjectStateManager of my parent object (which is already inserted) to Added and try to insert it. I’ve verified it in SQL Profiler and thus raises the exception of unique key violation.
I am getting rid of this in two ways
- Before adding the object I set all the navigational properties to null
- Set the
ObjectStateManagerof parent object toModified.
But this seems more like hack than a solution. I believe Entity Framework must have some elegant solution to this.
Kindly suggest.
The second approach is correct solution for this problem. When you call
AddObjectEF will attach all entities from the object graph inAddedstate. If you also have existing entities in the graph you must tell EF about them by either setting their state toUnchangedorModified.