-->

Part 52 - How to use Automapper in Asp.net MVC




In this video you will be able to know about how to use Automapper in  Asp.net MVC. 

#AutoMapper Initialization (AutomapperWebProfile.cs)
 Create a folder Infrastructure in the root folder of the project and create a class AutomapperWebProfile and copy below code into this.

using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTutorial.Infrastructure
{
public class AutomapperWebProfile : AutoMapper.Profile
{
public AutomapperWebProfile()
{

CreateMap<EmployeeDomainModel, EmployeeViewModel>();

CreateMap<EmployeeViewModel, EmployeeDomainModel>();

}

public static void Run()
{
AutoMapper.Mapper.Initialize(a =>
{
a.AddProfile<AutomapperWebProfile>();


});
}



}
}

#EmployeeDomainModel.cs 
Create below class into Model folder

 public class EmployeeDomainModel
{
public int EmployeeId { get; set; }
public string Name { get; set; }

}

# EmployeeViewModel.cs 

Create below class into Model folder

public class EmployeeViewModel
{
public int EmployeeId { get; set; }
public string Name { get; set; }

}


# Controller Code (TestController.cs)
Create a Test controller and in your Index method write below code. Here, I have added few record in EmployeeDomainModel and using AutoMapper, I copied data into EmployeeViewModel directly. In this way you can use Automapper. 

        public ActionResult Index()
{
List<EmployeeDomainModel> empDomainList = new List<EmployeeDomainModel>();

empDomainList.Add(new EmployeeDomainModel { EmployeeId = 1, Name = "Ashish" });
empDomainList.Add(new EmployeeDomainModel { EmployeeId = 2, Name = "Ajay" });

List<EmployeeViewModel> empVMList = new List<EmployeeViewModel>();

AutoMapper.Mapper.Map(empDomainList, empVMList);

return View();
}



#Global.asax file
Add below code into Application_Start() Method. to Initialize Automapper and to create map between source and destination folder. 

  AutomapperWebProfile.Run();

Thanks  . Keep Learning and Sharing

0 Response to "Part 52 - How to use Automapper in Asp.net MVC"

Post a Comment

Popular posts

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel