使用Value Injecter将int []转换为实体

时间:2015-07-20 02:14:10

标签: .net valueinjecter prodinner

在“ProDinner”项目中,ValueInjecter用于映射。我使用最新版本,在实体和int []之间进行转换时将ConventionInjection替换为LoopInjection,我得到了EntitiesToInts类的代码: / p>

public class EntitiesToInts : LoopInjection
{
    protected override bool MatchTypes(Type src, Type trg)
    {
        return trg == typeof(int[])
            && src.IsGenericType 
            && src.GetGenericTypeDefinition() == typeof(ICollection<>)
            && src.GetGenericArguments()[0].IsSubclassOf(typeof(Entity));
    }

    protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
    {
        var val = sp.GetValue(source);
        if (val != null)
        {
            tp.SetValue(target, (val as IEnumerable<Entity>).Select(o => o.Id).ToArray());
        }
    }
}

如何完成IntsToEntities课程?

1 个答案:

答案 0 :(得分:0)

IntsToEntities就在那里,您可以看到它在DefaultMapper类中的MapperConfig中使用

// go from int[] to ICollection<Entity> 
public class IntsToEntities : LoopInjection
{
    protected override bool MatchTypes(Type src, Type trg)
    {
        return src == typeof(int[]) 
            && trg.IsGenericType
            && trg.GetGenericTypeDefinition() == typeof(ICollection<>)
            && trg.GetGenericArguments()[0].IsSubclassOf(typeof(Entity));
    }

        protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
        {
            var sourceVal = sp.GetValue(source);
            if (sourceVal != null)
            {
                var tval = tp.GetValue(target);// make EF load the collection before modifying it; without it we get errors when saving an existing object

                dynamic repo = IoC.Resolve(typeof(IRepo<>).MakeGenericType(tp.PropertyType.GetGenericArguments()[0]));
                dynamic resList = Activator.CreateInstance(typeof(List<>).MakeGenericType(tp.PropertyType.GetGenericArguments()[0]));

                var sourceAsArr = (int[])sourceVal;
                foreach (var i in sourceAsArr)
                    resList.Add(repo.Get(i));

                tp.SetValue(target, resList);
            }
        }
    }