使用AutoMapper映射相同类型的多个集合属性

时间:2014-10-17 15:24:49

标签: automapper

我需要映射到属于同一类型对象集合的属性。

例如:

目的地:

public class MyNewObject
{
    Collection TypeCollection1 { get; set; }
    Collection TypeCollection2 { get; set; }
}

public class MyType
{
    string Field1 { get; set; }
    string Field2 { get; set; }
}

来源:

public class MyLegacyObject
{
    Collection LegacyCollection1 { get; set; }
    Collection LegacyCollection2 { get; set; }
}

public class MyLegacyType
{
    string OldField1 { get; set; }
    string OldField2 { get; set; }
}

对于非收藏品,我习惯这样做:

Mapper.CreateMap()
    .ForMember(dest => dest.TypeCollection1, opt => opt.MapFrom( 
        src => new Collection 
        {
            // is there some kind of ForEach thing I can do???
            Field1 = src.OldField1,
            Field2 = src.OldField2
            ??? // this obviously doesn't work because these are the properties on MyType, not the collection
        }));

1 个答案:

答案 0 :(得分:0)

Mapper.CreateMap<MyLegacyType, MyType>()
    .ForMember(dest => dest.Field1, opt => opt.MapFrom(src => src.OldField1))
    .ForMember(dest => dest.Field2, opt => opt.MapFrom(src => src.OldField2));
Mapper.CreateMap<MyLegacyObject, MyNewObject>()
    .ForMember(dest => dest.TypeCollection1, opt => opt.MapFrom(src => src.LegacyCollection1))
    .ForMember(dest => dest.TypeCollection2, opt => opt.MapFrom(src => src.LegacyCollection2))

我想我解决了自己的问题。这应该做到。