实体框架5实体的深层复制/克隆 [英] Entity Framework 5 deep copy/clone of an entity
问题描述
我正在使用Entity Framework 5( DBContext
),我试图找到深层复制实体(即复制实体和所有相关对象)的最佳方法,并且然后将新实体保存在数据库中。我怎样才能做到这一点?我已经研究过使用扩展方法,例如 CloneHelper
,但是我不确定它是否适用于 DBContext
。
I am using Entity Framework 5 (DBContext
) and I am trying to find the best way to deep copy an entity (i.e. copy the entity and all related objects) and then save the new entities in the database. How can I do this? I have looked into using extension methods such as CloneHelper
but I am not sure if it applies to DBContext
.
推荐答案
一种简单的克隆实体的简单方法是执行以下操作:
One cheap easy way of cloning an entity is to do something like this:
var originalEntity = Context.MySet.AsNoTracking()
.FirstOrDefault(e => e.Id == 1);
Context.MySet.Add(originalEntity);
Context.SaveChanges();
这里的诀窍是 AsNoTracking()-当您加载类似对此,您的上下文不知道,调用SaveChanges时,它将像对待新实体一样对待。
the trick here is AsNoTracking() - when you load an entity like this, your context do not know about it and when you call SaveChanges, it will treat it like a new entity.
如果 MySet
引用了 MyProperty
,并且您也想要它的副本,只需使用 Include
:
If MySet
has a reference to MyProperty
and you want a copy of it too, just use an Include
:
var originalEntity = Context.MySet.Include("MyProperty")
.AsNoTracking()
.FirstOrDefault(e => e.Id == 1);
这篇关于实体框架5实体的深层复制/克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!