If you already use AutoMapper on your projects, then you know why you do;) but I still meet many people (and some of them programming in C#) that do not know this great tool so wanted to share some thoughts.
There are many places in the code where you need to map from one class to another and in many cases these objects are similar or share some fields, this happens mostly between the application layers:
- Database entities are mapped into business logic DTO’s
- Business logic DTO’s are mapped into view-models
- And vice versa
For these mappings I have seen many ways how to map from one type to another: constructor which takes a source object instance, static mapper methods (factory methods), static mapping classes. These work fine, but usually require a repetitive work. There is another option – AutoMapper.
AutoMapper works in a way that at the application startup you define a static set of maps between pairs of classes and then define which property from the source maps to which property on the target. The map definition can look like this:
.ForMember(x => x.Id, map => map.MapFrom(x => x.Id)) // This can be skipped
.ForMember(x => x.IgnoredProperty, map => map.Ignore()) // Default value is used
.ForMember(x => x.ImageUrl, map => map.MapFrom(x => x.ProfileBlob != null ? x.ProfileBlob.FileUrl : null));
There are some conventions such as that the properties of the same name are mapped automatically without the need to define them explicitly and can be skipped.
And in the code when you want to map from one object instance to another you will just call:
var userViewModel = Mapper.Map<UserViewModel>(user);
What I like about this is that you have all the map definitions in one place and do hot have to write all the boring code for the physical mapping yourself. You still need to write the map definitions, but the code that needs to be written is minimized. If you keep the naming conventions you can skip the mapping of the fields with the same name. Even more complex mapping can be configured. AutoMapper support inheritance mapping and up to custom resolvers which can be also configured to work with IoC/DI, but this is more advanced topic.
I believe that using AutoMapper can simplify the code and increase the maintainability and that is the main reason I use it on my projects.