Automapper: bidirectional mapping with ReverseMap() and ForMember()

后端 未结 2 1834
野的像风
野的像风 2020-12-04 18:35

I have the case where I want to map an entity to a viewmodel and back. I have to specify the mapping explicitly with ForMember() because their properties do not

相关标签:
2条回答
  • 2020-12-04 19:17

    You could define your configuration like this:

    Mapper.CreateMap<PartTwo, PartTwoViewModel>()
        .ForMember(dst => dst.PartInteger, opt => opt.MapFrom(src => src.Integer));
    
    Mapper.CreateMap<PartTwoViewModel, PartTwo>()
        .ForMember(dst => dst.Integer, opt => opt.MapFrom(src => src.PartInteger));
    

    UPDATE

    Here is the commit where ReverseMap was initially implemented. From what I can see in the code, it only creates a simple reverse mapping. For example, in this case it would automatically configure the equivalent of:

    Mapper.CreateMap<PartTwoViewModel, PartTwo>();
    

    To get anything more complex, I'm afraid that you're going to have to configure it manually.

    0 讨论(0)
  • 2020-12-04 19:21

    ReverseMap returns an IMappingExpression that represents the reversal of the mapping. Once you call, it subsequent calls will be for configuring the reversal of the map.

    Here's an example:

    Mapper.CreateMap<CartItemDto, CartItemModel>()
          .ForMember(dest => dest.ExtendedCost, opt => opt.Ignore())
          .ReverseMap()
              .ForMember(dest => dest.Pricing, opt => opt.Ignore())
    

    This will ignore the Pricing field in the reverse direction.

    0 讨论(0)
提交回复
热议问题