Contents
Automapper is a simple reusable component which helps you to copy data from object type to other. If you wish to get automapper, read this.
For example, below is a simple employee
class loaded with some dummy data.
class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Salary { get; set; }
}
Employee emp = new Employee();
emp.FirstName = "Shiv";
emp.LastName = "Koirala";
emp.Salary = 100;
Now let’s say we want to load the above employee
data into a “Person
” class object.
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
So normally, developers end up writing mapping code as shown in the below snippet.
Person per = new Person();
per.FirstName = emp.FirstName;
per.LastName = emp.LastName;
At first glance, this does not look much of a problem but wait…think, what if you want to use this mapping code again and again.
So as a best practice, you would like to centralize this mapping code and reuse this mapping code again and again. This is where our super hero “AutoMapper
” comes to the rescue. “Automapper” sits in between both the objects like a bridge and maps the property data of both objects.
Using Automapper is a two-step process:
- Create the
Map
. - Use the
Map
so that objects can communicate.
Mapper.CreateMap<Employee, Person>();
Person per = Mapper.Map<Employee, Person>(emp);
In the above example property names of both classes are same so the mapping happens automatically.
If the classes have different property names, then we need to use “ForMember
” function to specify the mapping.
Mapper.CreateMap<Employee, Person>()
.ForMember(dest => dest.FName , opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LName , opt => opt.MapFrom(src => src.LastName));
- When you are moving data from
ViewModel
to Model
in projects like MVC. - When you are moving data from DTO to Model or entity objects and vice versa.
The easiest way is to use nugget. In case you are new to nuget, see this YouTube video.
Or you can download the component form their main site at http://automapper.org/.
Also, see following video on use of C# Automapper:
CodeProject
For Further reading do watch the below interview preparation videos and step by step video series.