复制具有层次结构的模型 [英] Duplicating a model that has a hierarchy

查看:61
本文介绍了复制具有层次结构的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型如下所示:

Company
-Locations

Locations
-Stores

Stores
-Products

因此,我想制作一个公司的副本,并且它的所有关联也应该复制并保存到数据库中。

So I want to make a copy of a Company, and all of its associations should also be copied and saved to the database.

如果我拥有公司加载到内存中?

How can I do this if I have the Company loaded in memory?

Company company = DbContext.Companies.Find(123);

如果比较棘手,我可以遍历每个关联,然后调用创建一个新对象。 ID会有所不同,但其他所有事物都应该相同。

If it is tricky, I can loop through each association and then call create a new object. The Id's will be different but everything else should be the same.

我正在使用EF 6。

推荐答案

使用EF克隆对象图简直是小菜一碟:

Cloning object graphs with EF is a piece of cake:

var company = DbContext.Companies.AsNoTracking()
                       .Include(c => c.Locations
                           .Select(l => l.Stores
                               .Select(s => s.Products)))
                       .Where(c => c.Id == 123)
                       .FirstOrDefault();
DbContext.Companies.Add(company);
DbContext.SaveChanges();

此处需要注意的几点。


  • AsNoTracking()非常重要,因为添加到上下文中的对象尚未被跟踪。

  • 现在,如果您 Add() 公司,则其对象图中的所有实体都将标记为已添加

  • 我假设数据库会生成新的主键值(标识列)。如果是这样,EF将忽略数据库中现有对象的当前值。如果不是这样,则必须遍历对象图并自己分配新值。

  • AsNoTracking() is vital, because the objects you add to the context shouldn't be tracked already.
  • Now if you Add() the company, all entities in its object graph will be marked as Added as well.
  • I assume that the database generates new primary key values (identity columns). If so, EF will ignore the current values from the existing objects in the database. If not, you'll have to traverse the object graph and assign new values yourself.

一个警告:只有当关联是1:0..n。如果存在n:m关联,则相同的实体可能会多次插入。例如,如果 Store-Product 是n:m,而产品A 出现在 store 1 商店2 产品A 将被插入两次。如果要防止这种情况,则应按一个上下文获取对象,具有跟踪(即不包含 AsNoTracking )和在新的上下文中> Add()。通过启用跟踪功能,EF可以跟踪相同的实体,并且不会重复它们。在这种情况下,应禁用代理创建,否则实体将保留对它们来自的上下文的引用。

One caveat: this only works well if the associations are 1:0..n. If there is a n:m association, identical entities may get inserted multiple times. If, for example, Store-Product is n:m and product A occurs at store 1 and store 2, product A will be inserted twice. If you want to prevent this, you should fetch the objects by one context, with tracking (i.e. without AsNoTracking), and Add() them in a new context. By enabling tracking, EF keeps track of identical entities and won't duplicate them. In this case, proxy creation should be disabled, otherwise the entities keep a reference to the context they came from.

更多详细信息,请参见:将相同的数据库合并为一个

More details here: Merge identical databases into one

这篇关于复制具有层次结构的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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