如何使用AutoMapper和ConstructUsing创建通用映射

时间:2017-01-18 16:25:22

标签: c# generics automapper

我有地图配置:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<IDictionary<int, MyType1>, List<MyType1>>().ConstructUsing(
        x0 => x0?.OrderBy(x => x.Key).Select(x => x.Value).ToList());
});

如何更改此选项以使用“所有MyTypes”?

我想针对任何T类型从IDictionary<int, T>转换为List<T>

我找到了一个非常难看的解决方案:

cfg.CreateMap(typeof(IDictionary<,>), typeof(List<>)).ConstructUsing(
    x0 =>
    {
        if (x0 == null)
        {
            return null;
        }

        var dict = (IEnumerable)x0;
        var type = x0.GetType().GetGenericArguments()[1];
        var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
        CastDictionaryEntry(dict).OrderBy(x => x.Key).ForEach(x => list.Add(x.Value));
        return list;
    }
);

static IEnumerable<DictionaryEntry> CastDictionaryEntry(IEnumerable dict)
{
    foreach (var item in dict)
    {
        yield return (DictionaryEntry)item;
    }
}

有没有更简单的方法呢?

1 个答案:

答案 0 :(得分:0)

我觉得有效,但我再没有对广泛的输入进行测试 -

class ABC
    {
        public int MyProperty { get; set; }
        public int MyProperty2 { get; set; }
    }
    static List<T> ConfigureMap<T>(Dictionary<int, T> input) where T : class
    {
        AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap(input.GetType(), typeof(List<T>))
        .ConstructUsing(Construct));

        return Mapper.Map<List<T>>(input);

    }

    private static object Construct(object arg1, ResolutionContext arg2)
    {
        if (arg1 != null)
        {
            var val = arg1 as IDictionary;
            var argument = val.GetType().GetGenericArguments()[1];
            if (val != null)
            {
                var type = Activator.CreateInstance(typeof(List<>).MakeGenericType(argument));

                foreach (var key in val.Keys)
                {
                    ((IList)type).Add(val[key]);
                }

                return type;
            }
        }

        return null;
    }

var so = new Dictionary<int, ABC> { { 1, new ABC { MyProperty = 10, MyProperty2 = 30 } } };
var dest = new List<ABC>();
var res = ConfigureMap<ABC>(so);