简体   繁体   English

AutoMapper映射复杂对象

[英]AutoMapper map complex object

I've been trying to use AutoMapper, but I'am having trouble configuring the map. 我一直在尝试使用AutoMapper,但是在配置地图时遇到了麻烦。

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. 如何映射A> ABC和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: 但是使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM