Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper - why use Map over DynamicMap?

Tags:

c#

automapper

Assuming the objects you're mapping with AutoMapper require no custom mappings, is there ever a point in doing this:

Mapper.CreateMap<Src, Dest>(); 
// ....
Mapper.Map(SrcObject, DestObj);

If no custom mappings are required, does the above approach gain you anything over just using DynamicMap without the need for any prior configuration?

Mapper.DynamicMap(SrcObject, DestObj);

I do understand that DynamicMap is required when you're mapping anonymous types, but I'm asking about whether DyanmicMap is ever not preferred for static types that require no custom mappings.

like image 552
Adam Rackis Avatar asked Mar 16 '12 15:03

Adam Rackis


People also ask

Is AutoMapper faster than manual mapping?

Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).

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.

Why do we use AutoMapper?

AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.


1 Answers

Been a while since I last used Automapper, but if I remember correctly:

In order to use Map, you need to specify those Maps explicitly first via CreateMap. Afterwards you can validate your Configuration by calling AssertConfigurationIsValid.

This happens right after launching your application rather than encountering an error mid execution (given that you create the mappings and validate on startup, which is recommended).

Also some types do not match 1:1, so you would want to specify the exact mappings, not sure if DynamicMap makes use of the Maps you have introduced manually, actually I think it does not.
Just checked, DynamicMap falls back on existing Maps in the current version up on github.

It's also a matter of performance since DynamicMap uses reflection more heavily than the Map method, since you have already specified the mapping configuration and most of it does not have to bee asserted on the fly anymore. Not sure if the new version of Automapper is performing caching in this regard by now though.

like image 93
ntziolis Avatar answered Nov 11 '22 02:11

ntziolis