EF6实体的通用克隆 [英] Generic Clone of EF6 Entity

查看:68
本文介绍了EF6实体的通用克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用EF6.0.2的通用CloneEntity函数

I am trying to get a generic CloneEntity function working with EF6.0.2

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

此代码来自此处

[更新]
我必须将声明更改为

[update] I had to change the declaration to

public static T CloneEntity<T>(T entity, bool copyKeys = false) where T : class

这解决了编译错误:'T'必须是引用类型可以在通用类型或方法中将其用作参数 T

This solved a compile error : 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method

但是,当我使用此方法时,没有将属性复制到新对象。

However when I use this method no properties are copied to the new object.

我不是先使用代码。我使用的对象是从edmx文件生成的。

I aren't using code first. The object I am using with it has been generated from the edmx file.

我正在使用的对象是从T4生成的

The kind of object I am using it with is generated from T4

public partial class job
{
    public short LineID { get; set; }
    public short CycleID { get; set; }
    // other fields 
}

我的DBContext就像

My DBContext is like

public partial class DataEntities : DbContext
{

    public DbSet<job> Jobs { get; set; }
}

[更新]

我尝试了

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)
    {

    }
}


推荐答案

我认为他们给了你一个盒子外面。尝试类似的操作:

I think they give you one out of the box. Try something like:

context.Entry(MyNewEntity).CurrentValues.SetValues(MyOldEntity);

这篇关于EF6实体的通用克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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