Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand you problem correctly, you are trying to save an object graph containing a ParentObject and related ChildObjects and you're getting the exception because Attach() is not able to reconcile Id collisions among the ChildObjects in the database and the attached ParentObject.</p> <p>Below is a work around I've used in the past. It's not pretty but it gets the job done.</p> <pre><code>public ParentObject Upsert(ParentObject newParentObject) { // Check for an existing ParentObject. ParentObject exisitingParentObject = container.ParentObjects.SingleOrDefault(o =&gt; o.Id == newParentObject.Id); // If not an existing ParentObject if (exisitingParentObject == null) { // Add a new ParentObject exisitingParentObject = container.ParentObjects.Add(container.ParentObjects.Create()); } // Update the properties of the existing ParentObject with the values of the new ParentObject var parentEntry = container.Entry(exisitingParentObject); parentEntry.CurrentValues.SetValues(newParentObject); // Remove ChildObjects that are in the existing but not in the new. for (int i = exisitingParentObject.ChildObjects.Count() - 1; i &gt;= 0; i--) { ChildObject exisitingChildObject = exisitingParentObject.ChildObjects[i]; if (!newParentObject.ChildObjects.Any(o =&gt; o.Id == exisitingChildObject.Id)) { container.ChildObjects.Remove(exisitingChildObject); } } // Upsert new ChildObjects foreach (ChildObject newChildObject in newParentObject.ChildObjects) { // Check for an existing ChildObject ChildObject exisitingChildObject = exisitingParentObject.SingleOrDefault(o =&gt; o.Id == newChildObject.Id); // If not an existing ChildObject if (exisitingChildObject == null) { // Add a new ChildObject exisitingChildObject = exisitingParentObject.ChildObjects.Add(container.ChildObject.Create()); } var childEntry = container.Entry(exisitingChildObject); childEntry.CurrentValues.SetValues(newChildObject); } container.SaveChanges(); return exisitingParentObject; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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