I have a ASP.NET MVC 3 application, using Entity Framework 4 to handle Data Access.
My View Model object structure looks like this:
public class OrderViewModel
{
public int Id { get; set; }
/* ... */
public List<OrderLineItemViewModel> LineItems { get; set; }
}
public class OrderLineItemViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
And, my Entity Framework Model looks like this:
public class Order
{
public int Id { get; set; }
/* ... */
public List<OrderLineItem> LineItems { get; set; }
}
public class OrderLineItem
{
public int Id { get; set; }
public string Name { get; set; }
}
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.
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...
What's the best approach to handling change tracking on child objects in Entity Framework, when converting from a View Model?
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...
Thanks!