Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC3 Parent-child relationships and Entity Framework, how to update children?
    text
    copied!<p>I have a ASP.NET MVC 3 application, using Entity Framework 4 to handle Data Access.</p> <p>My View Model object structure looks like this:</p> <pre><code>public class OrderViewModel { public int Id { get; set; } /* ... */ public List&lt;OrderLineItemViewModel&gt; LineItems { get; set; } } public class OrderLineItemViewModel { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>And, my Entity Framework Model looks like this:</p> <pre><code>public class Order { public int Id { get; set; } /* ... */ public List&lt;OrderLineItem&gt; LineItems { get; set; } } public class OrderLineItem { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>The thing that I am struggling with is how to handle editing an existing Order. My controller function will convert the Parent View Model into an Order object, and also convert the children (OrderLineItemViewModel) into the Entity Model (OrderLineItem). However, upon attaching the entity to the ObjectContext, it loses state of which Line Items have been changed, added, or deleted.</p> <p>All of the examples that I have found that address parent/child relationships seem to advocate not doing cascading updates to children, rather, preferring to have a seperate Controller Action and View for updating the child collection. However, I am trying to have the edit happen as one atomic operation... When the user hits "Edit Order" to submit the changes, I want the parent's fields to update, as well as handle any new/deleted/modified children...</p> <p>What's the best approach to handling change tracking on child objects in Entity Framework, when converting from a View Model?</p> <p>I have tried adding a IsNew, IsDirty, and IsDeleted to the ViewModel and the Model, then calling the appropriate function for each child (Attach, Delete or Add), but I get errors when trying to add saying that the child alreadys exists in the ObjectStateManager in an UnChanged state...</p> <p>Thanks!</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