Automapper:如何不重复从复杂类型到基类的映射配置

我有一堆inheritance自这个CardBase的DTO类:

 // base class public class CardBase { public int TransId {get; set; } public string UserId { get; set; } public int Shift { get; set; } } // one of the concrete classes public class SetNewCardSettings : CardBase { // specific properties ... } 

在我的MVC项目中,我有一堆具有AuditVm复杂类型的视图模型,它具有与CardBase相同的属性:

 public class AuditVm { public int TransId {get; set; } public string UserId { get; set; } public int Shift { get; set; } } public class CreateCardVm : CardVm { // specific properties here ... public AuditVm Audit { get; set } } 

这些视图模型无法从AuditVminheritance,因为它们中的每一个都已有父级。 我想我可以像下面那样设置我的映射,所以我CardBaseAuditVm作为复杂类型的每个视图模型指定AuditVmCardBase的映射。 但它没有用。 如何从复杂类型正确映射到具有基类属性的展平类型?

  Mapper.CreateMap() .Include(); // this does not work because it ignores my properties that I map in the second mapping // if I delete the ignore it says my config is not valid Mapper.CreateMap() .ForMember(dest => dest.Temp, opt => opt.Ignore()) .ForMember(dest => dest.Time, opt => opt.Ignore()); Mapper.CreateMap() // this gives me an error .ForMember(dest => dest, opt => opt.MapFrom(src => Mapper.Map(src.Auditor))); // I also tried this and it works, but it does not map my specific properties on SetNewCardSettings //.ConvertUsing(dest => Mapper.Map(dest.Auditor)); 

更新:这里是小提琴https://dotnetfiddle.net/iccpE0

.Include是一个非常具体的案例 – 你有两个相同结构的类层次结构,你想要映射,例如:

 public class AEntity : Entity { } public class BEntity : Entity { } public class AViewModel : ViewModel { } public class BViewModel : ViewModel { } Mapper.CreateMap() .Include() .Include(); // Then map AEntity and BEntity as well. 

所以,除非你遇到这种情况, .Include不适合使用。

我认为你最好的选择是使用ConstructUsing

  Mapper.CreateMap(); Mapper.CreateMap() .ConstructUsing(src => { SetNewCardSettings settings = new SetNewCardSettings(); Mapper.Map(src, settings); return settings; }) .IgnoreUnmappedProperties(); Mapper.CreateMap() .ConstructUsing(src => Mapper.Map(src.Audit)) .IgnoreUnmappedProperties(); 

我还结合了这个答案的扩展方法来忽略所有未映射的属性。 由于我们正在使用ConstructUsing ,因此AutoMapper不知道我们已经处理过这些属性。

更新小提琴: https //dotnetfiddle.net/6ZfZ3z