Introduction to AutoMapper
In our daily life as developers, we sometimes do some sort of repetitive coding that can be avoided by some sort of automation. Automapper is one such utility which helps developers to mapping of properties from one object to another. Typical examples for this scenario includes mapping of Domain entity to a DTO(Data Transfer Objects) , Model to a ViewModel. Normally this sort of mapping occurs at the boundary between the layers where we need to transfer data, say from Data Layer to Business Layer or from Business Layer to Presentation Layer.
In this example we have a class called Product which is a domain entity and we have another class called ProductViewModel which is a subset of the domain entity. So to transfer the data from the domain entity to the view model class we are manually mapping the properties one by one in line #17. The major drawbacks of these apporach are
- As the number of domain entities and their subset classes increases, the no of mappings needed also increases which is like a repetitive operation.
- Imagine a domain entity with a large number of members in it and we need to map most of them to another instance. It will become a time consuming process and in the process we may miss some properties and it will go unnoticed.
- When we deal with complex entities, the mapping part gets more tricky and make them hard to maintain.
- More the properties in an entity, the no of lines for mapping also increases which can be avoided.
- Another headache is with renaming of the properties. Whenever we change the name then we need to go to each mapping for this entity and make the change.
This is where AutoMapper comes in handy, it helps you to handle these kind of mapping scenarios in a generic way with minimal configuration. Using AutoMapper is your projects is very easy,
- You need to install it in your project using package manager/console.
- Create a mapping rule for transformation specifying source and destination entities by creating a MappingConfiguration object . The Mapper.Map method is now obselete in the latest version of AutoMapper and now we need to use the CreateMapper method in MappingConfiguration class for creating the mappings. Please read the excellent post by here on the recent changes in AutoMapper
- Perform transformation using by calling the Map method in MappingConfiguration class.
Let's see now how can we rewrite the above example to make use of AutoMapper's functionalities
Please tune back in to the blog for the rest of the parts in this series, till then Happy Coding !!!
Note: All these examples are based on 4.2.1 version of AutoMapper and there's some significant changes in library by removing the static API. Please refer here for futher details
Breaking Changes coming your way for ASP.NET Core 3.0
Resilient Connections in Entity Framework Core