我正在创建软件,用户可以根据旧产品创建新产品.
现在我需要使用Entity Framework进行复制/克隆操作.首先,我开始写这样的:
foreach(sourcedata1 in table1) { ... create new table ... copy data ... create Guid ... add foreach(sourcedata2 in table2) { ... create new table ... copy data ... create Guid ... add ... and so on } }
问题是,这不是一个很好的方法.是否有任何简单的方法克隆信息(除了需要为新行生成的Guid)或者我应该手动复制所有内容?
其他方案
您还可以使用EmitMapper或AutoMapper来复制属性.
Chr*_*l52 65
要在实体框架中克隆实体,您可以简单地从实体中分离实体DataContext
,然后将其重新添加到实体框架中EntityCollection
.
context.Detach(entity);
entityCollection.Add(entity);
Run Code Online (Sandbox Code Playgroud)
EF6 + 更新(来自评论)
context.Entry(entity).State = EntityState.Detached;
entity.id = 0;
entity.property = value;
context.Entry(entity).State = EntityState.Added;
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
kfm*_*000 15
使用直接序列化,您可以这样做:
使用Reflection,但需要更多代码,您可以执行此操作:http: //msmvps.com/blogs/matthieu/archive/2008/05/31/entity-cloner.aspx
Tom*_*asi 10
public static EntityObject Clone(this EntityObject Entity)
{
var Type = Entity.GetType();
var Clone = Activator.CreateInstance(Type);
foreach (var Property in Type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.SetProperty))
{
if (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>)) continue;
if (Property.PropertyType.IsGenericType && Property.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>)) continue;
if (Property.PropertyType.IsSubclassOf(typeof(EntityObject))) continue;
if (Property.CanWrite)
{
Property.SetValue(Clone, Property.GetValue(Entity, null), null);
}
}
return (EntityObject)Clone;
}
Run Code Online (Sandbox Code Playgroud)
这是我写的一个简单的方法.它适用于大多数人.
若要添加内容基于现有行的新行,请按照下列步骤操作:
这是一个例子:
var rabbit = db.Rabbits.First(r => r.Name == "Hopper");
db.Entry(rabbit).State = EntityState.Added;
rabbit.IsFlop = false;
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56730 次 |
最近记录: |