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> A.

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

谢谢。


我不确定你的意思是“我不想手动映射每个属性”。 但使用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);
链接地址: http://www.djcxy.com/p/37357.html

上一篇: AutoMapper map complex object

下一篇: Automapper Custom mapping or ignore