Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

.net - Automapper: bidirectional mapping with ReverseMap() and ForMember()

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 share the exact same names. Here is a short example of how my classes look like:

public class PartTwo {
    public int Integer { get; set; }
}

public class PartTwoViewModel {
    public int PartInteger { get; set; }
}

And I want to use them this way:

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

var partTwoViewModel = new PartTwoViewModel() { PartInteger = 42 };
var partTwo = Mapper.Map<PartTwoViewModel, PartTwo>(partTwoViewModel);
Assert.AreEqual(partTwoViewModel.PartInteger, partTwo.Integer);

But it does not match the property PartInteger to Integer. (Integer is 0.)

Is there a way to make this work? (When the properties of both classes have the same names it works.) Do I have to set some kind of option in the method ForMember()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...