将这些类视为源:
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);
最佳答案
您可以使用 .ConstructUsing
来完成此操作。它不是世界上看起来最干净的东西,但它会起作用:
/* Map each child to the destination */
Mapper.CreateMap<SourceChild1, Destination>();
Mapper.CreateMap<SourceChild2, Destination>();
Mapper.CreateMap<SourceParent, Destination>()
.ConstructUsing(src =>
{
/* Map A-D from Child1 */
var dest = Mapper.Map<Destination>(src.Child1);
/* Map I-L from Child2 */
Mapper.Map(src.Child2, dest);
return dest;
});
/* X will be mapped automatically. */
这应该会成功映射所有属性。
不幸的是,对 .AssertConfigurationIsValid
的调用将失败,因为属性 I
- L
不会映射到映射的目标类型从 SourceParent
→ Destination
。
当然,您可以为每个调用编写对 .Ignore
的调用,但这会破坏摆脱嵌套映射调用的目的。
您的另一个选择是利用 this awesome answer忽略每个映射上未映射的属性。
关于c# - AutoMapper 子对象中没有前缀名称的展平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26841112/