Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper: Does Map <A,B> give <B,A>?

Tags:

Using Automapper I create a simple map:

Mapper.CreateMap<MyCustomerDTO, YourCustomerDTO>()

I often need to go the other way too. Do I need to also create the mapping the other way, or will Automapper infer it based on the above mapping?

Mapper.CreateMap<YourCustomerDTO, MyCustomerDTO>()   //Needed?
like image 484
Ian Vink Avatar asked Dec 17 '12 17:12

Ian Vink


People also ask

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.

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

When should I use AutoMapper?

Use AutoMapper to eliminate the need to write tedious boilerplate code when mapping objects in your application. AutoMapper is a popular object-to-object mapping library that can be used to map objects belonging to dissimilar types.


2 Answers

This is a duplicate to Do i need to create automapper createmap both ways?

Note the answer regarding .ReverseMap() here.

Note that .ReverseMap() is for basic mapping. If you need to use options (such as specific ForMember mappings), you will need to create a custom reverse map.

like image 152
Mightymuke Avatar answered Oct 19 '22 17:10

Mightymuke


No. you must create two way mapping. A good helper method for two way mapping could be :

 protected virtual void ViceVersa<T1, T2>()
        {
            Mapper.CreateMap<T1, T2>();
            Mapper.CreateMap<T2, T1>();
        }

then use it like this :

ViceVersa<T1, T2>();
like image 25
Behnam Esmaili Avatar answered Oct 19 '22 17:10

Behnam Esmaili