我正在尝试获取与 EF6.0.2 一起使用的通用 CloneEntity 函数
public static T CopyEntity<T>(MyContext ctx, T entity,
bool copyKeys = false) where T : EntityObject
{
T clone = ctx.CreateObject<T>();
PropertyInfo[] pis = entity.GetType().GetProperties();
foreach (PropertyInfo pi in pis)
{
EdmScalarPropertyAttribute[] attrs = (EdmScalarPropertyAttribute[])
pi.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false);
foreach (EdmScalarPropertyAttribute attr in attrs)
{
if (!copyKeys && attr.EntityKeyProperty)
continue;
pi.SetValue(clone, pi.GetValue(entity, null), null);
}
}
return clone;
}
这段代码来自这里 http://www.codeproject.com/Tips/474296/Clone-an-Entity-in-Entity-Framework-4
[更新]
我不得不将声明更改为
public static T CloneEntity<T>(T entity, bool copyKeys = false) where T : class
这解决了编译错误:“T”必须是引用类型才能将其用作泛型类型或方法中的参数“T”
但是,当我使用此方法时,不会将任何属性复制到新对象。
我首先不使用代码。我使用的对象是从 edmx 文件生成的。
我使用它的对象类型是从 T4 生成的
public partial class job
{
public short LineID { get; set; }
public short CycleID { get; set; }
// other fields
}
我的 DBContext 就像
public partial class DataEntities : DbContext
{
public DbSet<job> Jobs { get; set; }
}
[Update]
I tried
using (var db = CreateDb())
{
var nJob = new job();
db.jobs.Attach(nJob);
db.Entry(nJob).CurrentValues.SetValues(job);
return nJob;
}
但我得到一个错误
"The property 'JobID' is part of the object's key information and cannot be modified. "
上下文是一个部分类
还有
partial class DataEntities
{
public DataEntities(string efConnectString)
: base(efConnectString)
{
}
}