Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do i need to create automapper createmap both ways?

This might be a stupid question! (n00b to AutoMapper and time-short!)

I want to use AutoMapper to map from EF4 entities to ViewModel classes.

1) If I call

CreateMap<ModelClass, ViewModelClass>() 

then do I also need to call

CreateMap<ViewModelClass, ModelClass>() 

to perform the reverse?

2) If two classes have the same property names, then do I need a CreateMap statement at all, or is this just for "specific/custom" mappings?

like image 508
BlueChippy Avatar asked May 31 '11 08:05

BlueChippy


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.

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

What layer should AutoMapper be?

It's on the outer layer but it only references the Core. In my case the infrastructure layer also houses Automapper. The core defines a simple interface (let's say IAutoMapper ) and a simple object that exists in the infrastructure implements it and the object can be passed to the UI layer through dependency injection.


2 Answers

For the info of the people who stumble upon this question. There appears to be now a built-in way to achieve a reverse mapping by adding a .ReverseMap() call at the end of your CreateMap() configuration chain.

like image 144
Ivan Zlatev Avatar answered Sep 28 '22 11:09

Ivan Zlatev


In AutoMapper you have a Source type and a Destination type. So you will be able to map between this Source type and Destination type only if you have a corresponding CreateMap. So to answer your questions:

  1. You don't need to define the reverse mapping. You have to do it only if you intend to map back.
  2. Yes, you need to call CreateMap to indicate that those types are mappable otherwise an exception will be thrown when you call Map<TSource, TDest> telling you that a mapping doesn't exist between the source and destination type.
like image 37
Darin Dimitrov Avatar answered Sep 28 '22 10:09

Darin Dimitrov