克隆实体框架实体

时间:2016-04-08 10:41:27

标签: c# entity-framework

我目前正在撰写将实体从一个用户帐户复制到另一个用户帐户的逻辑。我目前的策略是这样的: 请考虑以下代码:

 public class MobileOrderSettings:ICloneable
{
    public long Id { get; set; }
    public bool allowCash { get; set; }
    public int deliveryPrice { get; set; }
    public int deliveryTreshold { get; set; }
    public bool orderingEnabled { get; set; }
    public bool paymentsEnabled { get; set; }
    public int shippingType { get; set; }

    public virtual MobileApp MobileApp { get; set; }

    public object Clone()
    {
        var copy = CopyUtils.ShallowCopyEntity(this);
        copy.Id = default(int);
        copy.MobileApp = null;
        return copy;
    }
}

以这种方式定义的ShallowCopyEntity方法:

 public static TEntity ShallowCopyEntity<TEntity>(TEntity source) where TEntity : class, new()
    {

        // Get properties from EF that are read/write and not marked witht he NotMappedAttribute
        var sourceProperties = typeof(TEntity)
                                .GetProperties()
                                .Where(p => p.CanRead && p.CanWrite &&
                                            p.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.NotMappedAttribute), true).Length == 0);
        var notVirtualProperties = sourceProperties.Where(p => !p.GetGetMethod().IsVirtual);
        var newObj = new TEntity();

        foreach (var property in notVirtualProperties)
        {

            // Copy value
            property.SetValue(newObj, property.GetValue(source, null), null);

        }

        return newObj;

    }

因此,正如您所看到的,我首先复制所有非虚拟字段,重新写入Id值,然后执行依赖对象(集合)的副本(在此特定情况下,MobileOrderSettings依赖于MobileApp实体,因此我将MobileApp设为null ,在MobileApp Clone menthod中,我为MobileOrderSettings虚拟字段分配了MobileOrderSettings的副本。这种方法是好的,还是可以建议更好的解决方案?提前谢谢。

0 个答案:

没有答案