AutoMapper映射复杂对象

时间:2017-04-12 09:10:01

标签: c# automapper

我一直在尝试使用AutoMapper,但我在配置地图时遇到了问题。

有这个:

public class A
{
    public B b { get; set; }
    public C c { get; set; }
    public int id { get; set; }
    public string X { get; set; }
}

public class B
{
    public int id { get; set; }
    public string Y { get; set; }
}

public class C
{
    public int id { get; set; }
    public string Z { get; set; }
}

public class ABC
{
    public int Aid { get; set; }
    public string AX { get; set; }
    public int Bid { get; set; }
    public string BY { get; set; }
    public int Cid { get; set; }
    public string CZ { get; set; }
}

如何进行映射A> ABC和ABC>甲

我不想手动映射每个属性。有可能吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

我不确定你的意思是“我不想手动映射每个属性”。但是使用AutoMapper,您可以轻松映射属性:

        Mapper.Initialize(cfg => cfg.CreateMap<A, ABC>()
            .ForMember(dest => dest.AX, opt => opt.MapFrom(src => src.X))
            .ForMember(dest => dest.Aid, opt => opt.MapFrom(src => src.id))
            .ForMember(dest => dest.BY, opt => opt.MapFrom(src => src.b.Y))
            .ForMember(dest => dest.Bid, opt => opt.MapFrom(src => src.b.id))
            .ForMember(dest => dest.CZ, opt => opt.MapFrom(src => src.c.Z))
            .ForMember(dest => dest.Cid, opt => opt.MapFrom(src => src.c.id)));

        var a = new A
        {
            X = "I am A",
            id = 0,
            b = new B()
            {
                Y = "I am B",
                id = 1
            },
            c = new C()
            {
                Z = "I am C",
                id = 2
            }
        };

        var abc = Mapper.Map<A, ABC>(a);