Storing a complex detached object graph in EF6

detach entity-framework entity-framework-6 save

Question

I have the current scenario:

I'm using EF6 Code first, and have created a data-model something like this:

public class MainObject{
  ..some properties
  IList<SubObject> SubObjects{get;set;}
}

public class SubObject{
  ..some properties
  IList<SubSubObject> SubSubObjects{get;set;}
}

public class SubObject{
  ..some properties
  IList<SubObject> SubObjects{get;set;}
}

So basically I have a main object, that has 0 to many subobjects, and there is a many to many relationship between the subobject and the subsubobjects.

I am creating a MVC application, so my normal program flow is that the user request a page that basically uses a MainObject as it's data model. Then the user interacts with the page and changes, adds or removes subobjects and subsubobjects as he wishes, and then clicks save. On save, the objectgraph is sent back to the controller and it looks correct according to the changes done by the user on the client side. Now my problem is the following:

How to store this back into the database in a good fashion.

I need to attach my object back into the context, but I have no clue which objects are new, modified or deleted.

I have written some code that partially works now, but it's getting so ugly that I really don't want to go down that path. Would it be possible somehow to fetch the relevant object graph from the database, and have EF compare the two graphs toward eachother, and then save the relevant changes to the database?

Any help to make this smoother would be greatly appreciated.

1
7
2/10/2014 12:43:04 PM

Accepted Answer

I ended up using GraphDiff to solve this for me, and it works just great! This really should be built into EF, but untill it does, this is a great substitute.

To solve the example given in my question above, this will make sure that the detached graph gets saved properly (given I have a MainObject I want to save called main):

context.UpdateGraph(main, map =>map
  .AssociatedCollection( m => m.SubObjects, with => with
    .AssociatedCollection( s => s.SubSubObjects)
  )
);

context.SaveChanges();
7
2/11/2014 7:54:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow