2022
Implement AutoMapper in Asp.net MVC
538
AutoMapper
AutoMapper is a third party library that helps us to automate mapping between two similar kind of objects . For using that we can follow these steps.
First of all you have to install AutoMapper nuget package that you can see in the image below
Now click on install and it will ask for permissions to install automapper.
Once automapper is completely installed. You can add one new class in your project .
public class ProductDTO { public int ProductID { get; set; } public string ProductCategory { get; set; } public string SubCategory { get; set; } public string ProductName { get; set; } public string ProductDescription { get; set; } public decimal ProductPrice { get; set; } public decimal ProductWeight { get; set; } public int Units { get; set; } public decimal Total { get; set; } }
So this is the class we will use in automapper mapping. Now you have to add one new class MappingProfile for creating mappings.
using AutoMapper; using AutoMapperMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AutoMapperMVC { public static class Mapping { private static readonly Lazy<IMapper> Lazy = new Lazy<IMapper>(() => { var config = new MapperConfiguration(cfg => { // This line ensures that internal properties are also mapped over. cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.GetMethod.IsAssembly; cfg.AddProfile<MappingProfile>(); }); var mapper = config.CreateMapper(); return mapper; }); public static IMapper Mapper => Lazy.Value; } public class MappingProfile : Profile { public MappingProfile() { CreateMap<Product, Products>().ReverseMap(); //CreateMap<Product, ProductDTO>().ForMember(x => x.ProductName, opt => opt.MapFrom(y => y.ProductName)).ReverseMap(); //For custom mappings } } }
So in this class you can create map for all kind of objects using the CreateMap method . You can use RevereseMap() to enable reverse mappings.
Now go to your controller and add following code
using AutoMapper; using AutoMapperMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AutoMapperMVC.Controllers { public class HomeController : Controller { public HomeController() { } public ActionResult Index() { DbEmployeeEntities db = new DbEmployeeEntities(); List<Product> prodList = db.Products.ToList(); List<ProductDTO> products = new List<ProductDTO>(); foreach (var item in prodList) { products.Add( Mapping.Mapper.Map<ProductDTO>(item)); } return View(); } } }
So , here you can see how we are using the Mapper. You don't have to configure mapper for every place and you can simply use the Mapping.Mapper.Map() method wherever you want to use automapper.
So this is how we can implement AutoMapper in asp.net mvc.