omu.valueinjecter deep clone unlike types

后端 未结 2 685
心在旅途
心在旅途 2021-01-05 08:14

I think I\'m missing a simple concept with valueinjecter and/or AutoMapper, but how do you deep clone a parent dto.Entity to biz.Entity and include all children?

For

2条回答
  •  佛祖请我去吃肉
    2021-01-05 08:51

    I had this issue, even using the CloneInjection wasn't working to copy the properties with same name and diferent types. So I changed a few things in the CloneInjection (I'm using ValueInjecter version 3.1.3).

    public class CloneInjection : LoopInjection
    {
        protected override void Execute(PropertyInfo sp, object source, object target)
        {
            var tp = target.GetType().GetProperty(sp.Name);
            if (tp == null) return;
            var val = sp.GetValue(source);
            if (val == null) return;
    
            tp.SetValue(target, GetClone(sp, tp, val));
        }
    
        private static object GetClone(PropertyInfo sp, PropertyInfo tp, object val)
        {
            if (sp.PropertyType.IsValueType || sp.PropertyType == typeof(string))
            {
                return val;
            }
    
            if (sp.PropertyType.IsArray)
            {
                var arr = val as Array;
                var arrClone = arr.Clone() as Array;
    
                for (int index = 0; index < arr.Length; index++)
                {
                    var a = arr.GetValue(index);
                    if (a.GetType().IsValueType || a is string) continue;
    
                    arrClone.SetValue(Activator.CreateInstance(a.GetType()).InjectFrom(a), index);
                }
    
                return arrClone;
            }
    
            if (sp.PropertyType.IsGenericType)
            {
                //handle IEnumerable<> also ICollection<> IList<> List<>
                if (sp.PropertyType.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
                {
                    var genericType = tp.PropertyType.GetGenericArguments()[0];
    
                    var listType = typeof(List<>).MakeGenericType(genericType);
                    var list = Activator.CreateInstance(listType);
    
                    var addMethod = listType.GetMethod("Add");
                    foreach (var o in val as IEnumerable)
                    {
                        var listItem = genericType.IsValueType || genericType == typeof(string) ? o : Activator.CreateInstance(genericType).InjectFrom(o);
                        addMethod.Invoke(list, new[] { listItem });
                    }
    
                    return list;
                }
    
                //unhandled generic type, you could also return null or throw
                return val;
            }
    
            return Activator.CreateInstance(tp.PropertyType)
                .InjectFrom(val);
        }
    }
    

    I used like this:

    var entityDto = new EntityDto().InjectFrom(sourceEntity);
    

    I hope it helps!

提交回复
热议问题