Sunday, January 29, 2017

How to use AutoMapper

Here in this Post I will show How to use AutoMapper.
Before that what is the necessity to use AutoMapper, when we are using ViewModels in Asp.Net MVC we need to map each and every column individually.

Suppose take a table of Employee with multiple columns as shown.
(Table) Employee: ID, FirstName, LastName, Gender, Salary, DOJ and DeptID

(ViewModel) EmployeeVM:

public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public int Salary { get; set; }
public DateTime DOJ { get; set; }
public int DeptID { get; set; }

To Insert New Employee, we need to map (ViewModel) EmployeeVM and (Model) Employee as shown below.

public void ADDEmployee(EmployeeVM e)
 Employee emp = new Employee();
 emp.ID = e.ID;
 emp.FirstName = e.FirstName;
 emp.LastName = e.LastName;
 emp.Gender = e.Gender;
 emp.Salary = e.Salary;
 emp.DOJ = e.DOJ;


Supplose the Employee table had more columns like 20+... We need to map them one by one. Instead of doing that manually we will use AutoMapper.
Now Lets see how to use it for the above Employee table and EmployeeVM (ViewModel).

Create a Class and Name it as MappingConfig in App_Start Folder. ADD the below method in the class as below.

public class MappingConfig
 public static void RegisterMaps()
  AutoMapper.Mapper.Initialize(config =>
   config.CreateMap<Employee, EmployeeVM>();
   config.CreateMap<EmployeeVM, Employee>();

Now register the above class in Application_Start() method of Global.asax file as MappingConfig.RegisterMaps();
Now lets see how we can save simply with one line of code.

public void ADDEmployee(EmployeeVM e)
 Employee emp = Mapper.Map(e);

No comments:

Post a Comment