使用Automapper自定义解析器映射列表

时间:2014-06-16 05:23:41

标签: c# collections mapping automapper

我有2个对象需要相互映射。他们看起来像

public class Example1
{
     CustomType1 Prop { get; set; }
     List<CustomType1> List { get; set; } 
}

public class Example2
{
    Customtype2 Prop { get; set; }
    List<Customtype2> List { get; set; } 
}

public class CustomType1
{
    public string SomeString { get; set; }
}

public class Customtype2
{
    public string FirstPartOfSomeString { get; set; }

    public string SecondPartOfSomeString { get; set; }
}

我想制作一个将CustomType1映射到CustomType2的CustomResolver,然后在列表中使用该解析器。例如,

Mapper.CreateMap<Example1, Example2>()
            .ForMember(d => d.Prop, opt => opt.ResolveUsing(myCustomResolver))
            .ForMember(d => d.List, opt => opt.ResolveUsing( /*use myCustomResolver on a list here*/));

我尝试过使用类似的东西:

Mapper.CreateMap<Example1, Example2>()
            .ForMember(d => d.Prop, opt => opt.ResolveUsing(myCustomResolver))
            .ForMember(d => d.List, opt => opt.MapFrom(s => s.List.Select(myCustomResolver.Resolve).ToList()));

但我似乎错过了一些东西。有没有办法用AutoMapper做到这一点?

1 个答案:

答案 0 :(得分:1)

您是否尝试在自定义类型之间添加映射而不是使用解析程序? AutoMapper非常智能,可以重复使用列表映射...

Mapper.CreateMap<CustomType1, CustomType2>()
    .ForMember(x => FirstPartOfSomeString, opts => opts.MapFrom(x => x.SomeString.Substring(5)))
    .ForMember(x => SecondPartOfSomeString, opts => opts.MapFrom(x => x.SomeString.Substring(5, 5)));

Mapper.CreateMap<Example1, Example2>();