Question: When should I use ReverseMap with Automapper?
When working with Automapper, there are certain circumstances in which it is beneficial to use the ReverseMap
method. This method simplifies the mapping process, but should not be used for complex mappings or when mapping deeply nested objects.
For example, when mapping between my DB Entities and Models, I can use ReverseMap
to map between my primary classes such as Document
and DocumentModel
, as well as between Element
and ElementModel
. However, when mapping between derived classes such as ElementText
and ElementTextModel
, ReverseMap
will only map to the base class (Element
and ElementModel
). To ensure the derived class mapping is successful, IncludeAllDerived
should be used in conjunction with ReverseMap
.
In more complex cases, it is best to avoid ReverseMap
and explicitly define mappings in both directions, e.g. CreateMap<ElementModel, Element>().IncludeAllDerived()
. This will ensure all the desired mappings are successful.