Monday, April 27, 2015

What is Automapper?

Contents

What is Automapper ?

I have not specified mapping how does it work ?

How can we map different property names in Automapper ?

Can you give some real time scenarios of the use of Automapper ?

From where to get AutoMapper ?


What is Automapper ?


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; }
}
// Loaded with some data
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 in to 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 the 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 for rescue.“Automapper” sits in between both the objects like a bridge and maps the property data of both objects.


Using Automapper is a two-stepprocess:-
  • Create the Map.
  • Use the Map so that objects can communicate.
Mapper.CreateMap(); // Create Map
Person per =  Mapper.Map(emp); // Use the map

I have not specified mapping how does it work ?


In the above example property names of both classes are same so the mapping happens automatically.

How can we map different property names in Automapper ?


If the classes have different property names then we need to use “ForMember” function to specify the mapping.
Mapper.CreateMap()
.ForMember(dest => dest.FName , opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LName , opt => opt.MapFrom(src => src.LastName));

Can you give some real time scenarios of the use of Automapper ?

  • 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.

From where to get AutoMapper ?


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 http://automapper.org/