C# 自动映射复杂对象

C# 自动映射复杂对象,c#,automapper,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

我一直在尝试使用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);

通常,automapper希望属性名称相同。对于不同的名称,您需要配置映射。因此,在您的情况下,您必须映射automapper中的每个属性。不必配置映射就可以更改为什么?是否可以设置一些映射规则?拥有很多财产。。。