Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 606
toni Avatar asked Nov 21 '12 09:11

toni


People also ask

Is AutoMapper bidirectional?

What is AutoMapper Reverse Mapping in C#? The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping.

What does ReverseMap do in AutoMapper?

By calling ReverseMap , AutoMapper creates a reverse mapping configuration that includes unflattening: var customer = new Customer { Name = "Bob" }; var order = new Order { Customer = customer, Total = 15.8m }; var orderDto = mapper.

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.


1 Answers

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.

like image 105
Jon Wingfield Avatar answered Oct 14 '22 16:10

Jon Wingfield