将实体对象复制到POCO对象,其中实体整数是POCO上的枚举

时间:2014-07-08 20:01:59

标签: c# entity-framework enums linq-expressions

我尝试使用Jon Skeets属性副本创建复印机。它适用于所有属性,但不适用于枚举。我已经尝试过多次尝试将这种方法改为枚举,但收效甚微。我想知道是否有其他人可能知道如何做到这一点。

Jon Skeets原创,我的修改与BUILDCOPIER方法中的评论分开了

对此的调用是

        var result = Common.PropertyCopy<POCO>.CopyFrom(Entity);

原始Jon Skeet代码

/// <summary>
/// Generic class which copies to its target type from a source
/// type specified in the Copy method. The types are specified
/// separately to take advantage of type inference on generic
/// method arguments.
/// http://www.yoda.arachsys.com/csharp/miscutil/
/// </summary>
public static class PropertyCopy<TTarget> where TTarget : class, new()
{
    /// <summary>
    /// Copies all readable properties from the source to a new instance
    /// of TTarget.
    /// </summary>
    public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
    {
        return PropertyCopier<TSource>.Copy(source);
    }

    /// <summary>
    /// Static class to efficiently store the compiled delegate which can
    /// do the copying. We need a bit of work to ensure that exceptions are
    /// appropriately propagated, as the exception is generated at type initialization
    /// time, but we wish it to be thrown as an ArgumentException.
    /// </summary>
    private static class PropertyCopier<TSource> where TSource : class
    {
        private static readonly Func<TSource, TTarget> copier;
        private static readonly Exception initializationException;

        internal static TTarget Copy(TSource source)
        {
            if (initializationException != null)
            {
                throw initializationException;
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            return copier(source);
        }

        static PropertyCopier()
        {
            try
            {
                copier = BuildCopier();
                initializationException = null;
            }
            catch (Exception e)
            {
                copier = null;
                initializationException = e;
            }
        }

        private static Func<TSource, TTarget> BuildCopier()
        {
            ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
            var bindings = new List<MemberBinding>();
            foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())
            {
                if (!sourceProperty.CanRead)
                {
                    continue;
                }
                PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
                if (targetProperty == null)
                {
                    throw new ArgumentException("Property " + sourceProperty.Name + " is not present and accessible in " + typeof(TTarget).FullName);
                }
                if (!targetProperty.CanWrite)
                {
                    throw new ArgumentException("Property " + sourceProperty.Name + " is not writable in " + typeof(TTarget).FullName);
                }

                // THIS IS FALSE FOR SOURCE(INT) TARGET ENUMS
                if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                {
                    //ADDED FOLLOWING TO HANDLE COPY FROM INT TO ENUM
                    /////////////////////////////////////////////////////////////////////////////////////////////////////
                    // Special Case because Entities are created with property as ints, not enum types
                    if (targetProperty.PropertyType.IsEnum && (sourceProperty.PropertyType == typeof(int)))
                    {
                        var expressionparam = Expression.Parameter(sourceProperty.PropertyType);
                        // cast the entity source as the enum target
                        var cast = Expression.Convert(expressionparam, targetProperty.PropertyType);
                        // add to the binding tree
                        bindings.Add(Expression.Bind(targetProperty, Expression.Property(cast, sourceProperty)));
                        continue;
                    }
                    /////////////////////////////////////////////////////////////////////////////////////////////////////

                    throw new ArgumentException("Property " + sourceProperty.Name + " has an incompatible type in " + typeof(TTarget).FullName);
                }
            Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
            return Expression.Lambda<Func<TSource, TTarget>>(initializer, sourceParameter).Compile();
        }
    }
}

枚举

public enum NotificationType
{
    InAppNotificiation = 0,
    EmailNotification,
    SMS
}

EF生成的实体类

public class Entity
{
    public int ProcessedStatus { get; set; }
    public int Priority { get; set; }
    public System.Guid NotifyToUserId { get; set; }
    public string NotifyFrom { get; set; }
    public string NotifySubject { get; set; }
    public string NotifyMessageBody { get; set; }
    public int NotificationType { get; set; }  <-- Stored as int in DB

     public virtual MercuryUser MercuryUser { get; set; } <--complex type
}

POCO课程

public class POCO
{
    public int ProcessedStatus { get; set; }
    public int Priority { get; set; }
    public System.Guid NotifyToUserId { get; set; }
    public string NotifyFrom { get; set; }
    public string NotifySubject { get; set; }
    public string NotifyMessageBody { get; set; }
    public NotificationType NotificationType { get; set; }  <-- ENUM TYPE

    public MyUser MyUser { get; set; } <-- complex type
}

抛出异常
bindings.Add(Expression.Bind(targetProperty, Expression.Property(cast, sourceProperty)));

Property&#39; Int32 NotificationType&#39;未定义类型&#39; Models.Enums.NotificationType

1 个答案:

答案 0 :(得分:0)

所以我找到了这篇文章C# Using Reflection to copy base class properties并尝试了这个,有时简单只是工作......不确定为什么这个会设置枚举,也不会炸掉复杂的类型。也许就是lambda表达式如何解释对象。它不会检查是否可以为任何东西分配,特别是枚举类型,它只是根据int和属性名称设置它。如果isAssignable在尝试从int类型的sourceproperty和基础类型相同的enum类型的targetproperty进行设置时表示NO,则表示直观。如果有人能够对此有所了解,那将是很好的,现在我将使用下面列出的更简单的复制方法。低端是它不会缓存复印机,所以它必须每次都通过它。

    public static T1 CopyFrom<T1, T2>(T1 obj, T2 otherObject) where T1 : class where T2 : class
    {
        PropertyInfo[] srcFields = otherObject.GetType().GetProperties(
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);

        PropertyInfo[] destFields = obj.GetType().GetProperties(
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);

        foreach (var property in srcFields)
        {
            var dest = destFields.FirstOrDefault(x => x.Name == property.Name);
            if (dest != null && dest.CanWrite)
                dest.SetValue(obj, property.GetValue(otherObject, null), null);
        }

        return obj;
    }