在 EF6 中存储复杂的分离对象图 [英] Storing a complex detached object graph in EF6

查看:13
本文介绍了在 EF6 中存储复杂的分离对象图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有当前的场景:

我首先使用 EF6 代码,并创建了一个类似这样的数据模型:

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;}
}

所以基本上我有一个主对象,它有 0 到多个子对象,并且子对象和子子对象之间存在多对多关系.

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.

我正在创建一个 MVC 应用程序,所以我的正常程序流程是用户请求一个基本上使用 MainObject 作为其数据模型的页面.然后用户与页面交互并随心所欲地更改、添加或删除子对象和子子对象,然后单击保存.保存时,对象图被发送回控制器,根据用户在客户端所做的更改,它看起来是正确的.现在我的问题如下:

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.

我已经编写了一些现在可以部分工作的代码,但它变得如此丑陋,以至于我真的不想走这条路.是否有可能以某种方式从数据库中获取相关的对象图,并让 EF 将两个图相互比较,然后将相关更改保存到数据库中?

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.

推荐答案

我最终使用 GraphDiff 为我解决了这个问题,而且效果很好!这确实应该内置到 EF 中,但在它内置之前,这是一个很好的替代品.

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.

为了解决上面我的问题中给出的示例,这将确保正确保存分离的图形(假设我有一个 MainObject 我想保存称为 main):

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

这篇关于在 EF6 中存储复杂的分离对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆