将这些类视为源:
public class SourceParent
{
public int X { get; set; }
public SourceChild1 Child1 { get; set; }
public SourceChild2 Child2 { get; set; }
}
public class SourceChild1
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public int D { get; set; }
}
public class SourceChild2
{
public int I { get; set; }
public int J { get; set; }
public int K { get; set; }
public int L { get; set; }
}
我正在尝试将源映射到类似于此的目标:
public class Destination
{
public int X { get; set; }
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public int D { get; set; }
public int I { get; set; }
public int J { get; set; }
public int K { get; set; }
public int L { get; set; }
}
好吧,使用这个配置,可以进行映射:
Mapper.CreateMap<SourceParent, Destination>()
.ForMember(d => d.A, opt => opt.MapFrom(s => s.Child1.A))
.ForMember(d => d.B, opt => opt.MapFrom(s => s.Child1.B))
.ForMember(d => d.C, opt => opt.MapFrom(s => s.Child1.C))
.ForMember(d => d.D, opt => opt.MapFrom(s => s.Child1.D))
.ForMember(d => d.I, opt => opt.MapFrom(s => s.Child2.I))
.ForMember(d => d.J, opt => opt.MapFrom(s => s.Child2.J))
.ForMember(d => d.K, opt => opt.MapFrom(s => s.Child2.K))
.ForMember(d => d.L, opt => opt.MapFrom(s => s.Child2.L));
除此之外,当子类具有许多属性,所有属性与父级具有相同的名称时,这不是一种干净的方式。
理想情况下,我想告诉AutoMapper将Source.Child1和Source.Child2作为源,并将每个匹配的属性名称映射到目标(而不是指定每个属性);这样的事情:
Mapper.CreateMap<SourceParent, Destination>()
.AlsoUseSource(s => s.Child1)
.AlsoUseSource(s => s.Child2);