AutoMapper — inheritance mapping not working, same source, multiple destinations

前端 未结 2 512
挽巷
挽巷 2020-12-31 10:12

Can I use inheritance mapping in AutoMapper (v2.2) for maps with the same Source type but different Destination types?

I have this basic situation (the real classes

2条回答
  •  滥情空心
    2020-12-31 10:35

    Unfortunately in this case, AutoMapper seems to be registering only one child class mapping per source type, the last one (ViewModelB). This was probably designed to work with parallel hierarchies, not with a single source type.

    To work around this, you can encapsulate the common mappings in an extension method:

    public static IMappingExpression MapBaseViewModel(this IMappingExpression map)
      where TDestination : BaseViewModel { 
      return map.ForMember(x => x.CommonProperty, y => y.MapFrom(z => z.Property1));
    }
    

    And use it in the individual subclass mappings:

    Mapper.CreateMap()
      .MapBaseViewModel()
      .ForMember(x => x.PropertyA, y => y.MapFrom(z => z.Property2));
    
    Mapper.CreateMap()
      .MapBaseViewModel()
      .ForMember(x => x.PropertyB, y => y.MapFrom(z => z.Property3));
    

提交回复
热议问题