使用automapper将多个对象映射到一个对象

时间:2016-02-04 16:18:13

标签: automapper

是否可以使用automapper将一个对象映射到多个对象?我知道可以反过来实现here

1 个答案:

答案 0 :(得分:2)

一种方法:

Mapper.CreateMap<MAINSource, MAINDest>()
    .ForMember(dest => dest.Inner1, expression => expression.ResolveUsing(source1 => source1.Inner1))
    .ForMember(dest => dest.Inner2, expression => expression.ResolveUsing(source1 => source1.Inner2));


Mapper.CreateMap<Source1, Dest1>()
    .ForMember(dest => dest.NumValue, expression => expression.ResolveUsing(source1 => source1.NumValue));
Mapper.CreateMap<Source1, Dest2>()
    .ForMember(dest => dest.StringValue, expression => expression.ResolveUsing(source1 => source1.StringValue));

完整示例:

public class Source1
{
    public int NumValue { get; set; }
    public string StringValue { get; set; }
}

public class MAINSource
{
    public Source1 Inner1 { get; set; }
    public Source1 Inner2 { get; set; }
}

public class Dest1
{
    public int NumValue { get; set; }
}

public class Dest2
{
    public string StringValue { get; set; }
}

public class MAINDest
{
    public Dest1 Inner1 { get; set; }
    public Dest2 Inner2 { get; set; }
}


Mapper.CreateMap<MAINSource, MAINDest>()
    .ForMember(dest => dest.Inner1, expression => expression.ResolveUsing(source1 => source1.Inner1))
    .ForMember(dest => dest.Inner2, expression => expression.ResolveUsing(source1 => source1.Inner2));


Mapper.CreateMap<Source1, Dest1>()
    .ForMember(dest => dest.NumValue, expression => expression.ResolveUsing(source1 => source1.NumValue));
Mapper.CreateMap<Source1, Dest2>()
    .ForMember(dest => dest.StringValue, expression => expression.ResolveUsing(source1 => source1.StringValue));

var innerSource = new Source1 {NumValue = 1, StringValue = "supervalue"};
var mainSource = new MAINSource
{
    Inner1 = innerSource,
    Inner2 = innerSource
};


var destination = Mapper.Map<MAINSource, MAINDest>(mainSource);

destination.Inner1.NumValue.ShouldEqual(1);
destination.Inner2.StringValue.ShouldEqual("supervalue");