Salin objek Entitas ke objek POCO di mana int Entitas adalah Enum di POCO

Saya mencoba membuat mesin fotokopi menggunakan salinan properti Jon Skeets. Ini berfungsi dengan baik untuk semua properti, tetapi tidak untuk enum. Saya telah mencoba beberapa upaya untuk mengubah metode agar berfungsi untuk enum dan tidak berhasil. Saya bertanya-tanya apakah ada orang lain yang punya ide tentang cara melakukan ini.

Jon Skeets asli, dengan perubahan saya dipotong dengan komentar dalam metode BUILDCOPIER

panggilan untuk ini adalah

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

Kode Jon Skeet asli

/// <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();
        }
    }
}

enum

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

Kelas Entitas yang dihasilkan oleh 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
}

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

Pengecualian dilemparkan ke garis

bindings.Add(Expression.Bind(targetProperty, Expression.Property(cast, sourceProperty)));

Properti 'Int32 NotificationType' tidak ditentukan untuk tipe 'Models.Enums.NotificationType


person DRobertE    schedule 08.07.2014    source sumber
comment
EF mendukung POCO dan enum yang mengutamakan kode (sejak versi 5) sehingga Anda tidak perlu lagi menyalin satu objek ke objek lainnya.   -  person Panagiotis Kanavos    schedule 09.07.2014
comment
Keputusan desain dibuat sebelum saya datang ke proyek dan kode terlebih dahulu tidak digunakan.   -  person DRobertE    schedule 09.07.2014
comment
Bukankah Anda secara efektif mereplikasi kode terlebih dahulu ketika Anda menulis kelas target? Bagaimanapun, Anda dapat menggunakan perpustakaan pemetaan seperti AutoMapper untuk memetakan satu DTO ke DTO lainnya tanpa menulis sendiri kode refleksinya. Pustaka pemetaan juga menangani pemetaan cache sehingga Anda tidak perlu mengulangi pencarian properti setiap kali ingin memetakan objek baru   -  person Panagiotis Kanavos    schedule 09.07.2014


Jawaban (1)


Jadi saya menemukan posting ini C# Menggunakan Refleksi untuk menyalin properti kelas dasar dan mencoba ini sebagai gantinya, terkadang yang sederhana hanya berhasil... tidak yakin mengapa yang ini akan mengatur enum dan juga tidak meledak pada tipe yang kompleks. Mungkin begitulah ekspresi lambda menafsirkan objek. Itu tidak memeriksa apakah dapat ditugaskan dari apa pun, khususnya tipe enum, itu hanya mengaturnya berdasarkan int dan nama properti. Agak kontra intuitif jika isAssignable mengatakan TIDAK ketika mencoba menyetel dari properti sumber bertipe int dan properti target bertipe enum ketika tipe dasarnya sama. Jika ada yang bisa memberikan wawasan tentang hal ini, itu bagus sekali, untuk saat ini saya akan menggunakan metode penyalinan yang lebih sederhana yang tercantum di bawah. Sisi negatifnya adalah mesin fotokopi tidak menyimpan cache sehingga harus memeriksanya setiap saat.

    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;
    }
person DRobertE    schedule 09.07.2014