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?
Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .
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.
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.
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.
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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With