如何将多个对象映射到具有源对象作为属性的单个对象?

时间:2015-02-26 11:26:00

标签: c# automapper

我有以下模型。

public class MainModel
{
    public object1 Property1{get; set;}
    public object2 Property2{get; set;}
    public object3 Property3{get; set;}
}

Public class object1{
    /// few properties;
}

Public class object2{
    /// few properties;
}

Public class object3{
    /// few properties;
}

现在如何使用AutoMapper将这些多个对象映射到MainModel?

1 个答案:

答案 0 :(得分:0)

Mapper.CreateMap<object1, MainModel>()
                        .ForMember(x => x.Property1, y => y.MapFrom(src => src));
Mapper.CreateMap<object2, MainModel>()
                      .ForMember(x => x.Property2, y => y.MapFrom(src => src));
Mapper..CreateMap<object3, MainModel>()
                   .ForMember(x => x.Property3, y => y.MapFrom(src => src));


object1 obj1 = new object1();
object2 obj2 = new object2();
object3 obj3 = new object3();

MainModel mm = AutoMapper.Mapper.Map<MainModel>(obj1);
mm = AutoMapper.Mapper.Map(obj2, mm);
mm = AutoMapper.Mapper.Map(obj3, mm);