AutoMapper map complex object

I've been trying to use AutoMapper, but I'am having trouble configuring the map.

Having this:

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; }
}

How can I do mapping A > ABC and ABC > A.

I don't want to map each property manually. Is it possible?

Thank you.


I am not sure what you mean by "I don't want to map each property manually". But with AutoMapper you could easily map the properties:

        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/37358.html

上一篇: Automapper。 如果源成员为空,则映射

下一篇: AutoMapper映射复杂对象