Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

entity framework - Storing a complex detached object graph in EF6

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...