Using Auto-Mapper In An ASP.NET Core MVC Application

Introduction

 
In today’s article we will look at an extremely useful feature. In many applications, the data we collect on the user interface needs to be converted to some different form before it can be stored in the data store and vice versa. This requires some mapping logic and it is mostly done using mapping classes and logic. Today, we will look at a ready to use Nuget package to do this mapping for us and make the process amazingly simple. We will apply this mapping in an ASP.NET Core MVC application.

Creating the .NET Core MVC application

 
We will start by creating an ASP.NET Core 3.1 MVC application using Visual Studio 2019 community edition as below,
 
Using Auto-Mapper in an ASP.NET Core MVC application
 
We select the ASP.NET Core web application and click “Next”
 
Using Auto-Mapper in an ASP.NET Core MVC application
 
Next, we enter the project details and click “Create”
 
Using Auto-Mapper in an ASP.NET Core MVC application
 
From the list of ASP.NET Core web applications, we select “Web Application (Model-View-Controller) and leave all other values as default.
 
We now have the ASP.NET Core MVC application created. The next step is to add the “AutoMapper” Nugget package as below,
 
Using Auto-Mapper in an ASP.NET Core MVC application
 
Remember to select the latest version.
 
Using Auto-Mapper in an ASP.NET Core MVC application
 
After that create three classes under the “Models” folder as below,
 
Employee.cs 
  1. namespace WebAppAutoMapper.Models {  
  2.     publicclassEmployee {  
  3.         publicstring FirstName {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         publicstring LastName {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         publicstring StreetAddress {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         publicstring City {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         publicstring Province {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         publicstring Country {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         publicstring Email {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         publicstring Phone {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         publicEmployee() {  
  36.             FirstName = "Munib";  
  37.             LastName = "Butt";  
  38.             StreetAddress = "123 Street One";  
  39.             City = "Toronto";  
  40.             Province = "Ontario";  
  41.             Country = "Canada";  
  42.             Email = "test@hotmail.com";  
  43.             Phone = "+14161112222";  
  44.         }  
  45.     }  
  46. }  
EmployeeDTO.cs
  1. namespace WebAppAutoMapper.Models {  
  2.     publicclassEmployeeDTO {  
  3.         publicstring Name {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         publicstring Address {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         publicstring Email {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         publicstring Phone {  
  16.             get;  
  17.             set;  
  18.         }  
  19.     }  
  20. }  
And finally,AutoMap.cs
  1. using AutoMapper;  
  2.   
  3. namespace WebAppAutoMapper.Models  
  4. {  
  5. publicclassAutoMap : Profile  
  6.     {  
  7. publicAutoMap()  
  8.         {  
  9.             CreateMap<Employee, EmployeeDTO>() // means you want to map from Employee to EmployeeDTO  
  10.             .ForMember(d => d.Name, source => source.MapFrom(s => s.FirstName + " " + s.LastName))  
  11.             .ForMember(d => d.Address, source => source.MapFrom(s => s.StreetAddress + ", " + s.City + ", " + s.Province + ", " + s.Country))  
  12.             .ForMember(d => d.Phone, source => source.MapFrom(s => s.Phone))  
  13.             .ForMember(d => d.Email, source => source.MapFrom(s => s.Email));  
  14.         }  
  15.     }  
  16. }  
Here we see that we have an Employee class which has several properties. We also have an EmployeeDTO class which has fewer properties than the Employee class. Now, we want to map the values from the Employee class to the EmployeeDTO class using some mapping logic. This logic is implemented in the AutoMap.cs class which inherits from the Profile class.
 
Finally, we setup the AutoMap in the Startup.cs class in the “ConfigureServices” function as below,
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Hosting;  
  6. using AutoMapper;  
  7. using WebAppAutoMapper.Models;  
  8.   
  9. namespace WebAppAutoMapper  
  10. {  
  11. publicclassStartup  
  12.     {  
  13. publicStartup(IConfiguration configuration)  
  14.         {  
  15.             Configuration = configuration;  
  16.         }  
  17.   
  18. public IConfiguration Configuration { get; }  
  19.   
  20. // This method gets called by the runtime. Use this method to add services to the container.  
  21. publicvoid ConfigureServices(IServiceCollection services)  
  22.         {  
  23.             services.AddAutoMapper(c => c.AddProfile<AutoMap>(), typeof(Startup));  
  24.             services.AddControllersWithViews();  
  25.         }  
  26.   
  27. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  28. publicvoid Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  29.         {  
  30. if (env.IsDevelopment())  
  31.             {  
  32.                 app.UseDeveloperExceptionPage();  
  33.             }  
  34. else  
  35.             {  
  36.                 app.UseExceptionHandler("/Home/Error");  
  37. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
  38.                 app.UseHsts();  
  39.             }  
  40.             app.UseHttpsRedirection();  
  41.             app.UseStaticFiles();  
  42.   
  43.             app.UseRouting();  
  44.   
  45.             app.UseAuthorization();  
  46.   
  47.             app.UseEndpoints(endpoints =>  
  48.             {  
  49.                 endpoints.MapControllerRoute(  
  50.                     name: "default",  
  51.                     pattern: "{controller=Home}/{action=Index}/{id?}");  
  52.             });  
  53.         }  
  54.     }  
  55. }  
Now, all the plumbing is in place and we can use the mapping as below in the Home Controller,
  1. using System.Diagnostics;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.Extensions.Logging;  
  4. using WebAppAutoMapper.Models;  
  5. using AutoMapper;  
  6.   
  7. namespace WebAppAutoMapper.Controllers  
  8. {  
  9. publicclassHomeController : Controller  
  10.     {  
  11. privatereadonly ILogger<HomeController> _logger;  
  12. privatereadonly IMapper _mapper;  
  13.   
  14. publicHomeController(ILogger<HomeController> logger, IMapper mapper)  
  15.         {  
  16.             _logger = logger;  
  17.             _mapper = mapper;  
  18.         }  
  19.   
  20. public IActionResult Index()  
  21.         {  
  22.             Employee emp = new Employee();  
  23. var empDTO = _mapper.Map<EmployeeDTO>(emp);  
  24. return View();  
  25.         }  
  26.   
  27. public IActionResult Privacy()  
  28.         {  
  29. return View();  
  30.         }  
  31.   
  32.         [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]  
  33. public IActionResult Error()  
  34.         {  
  35. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });  
  36.         }  
  37.     }  
  38. }  
We can put a breakpoint at the “return View();” line in the Index function and see the Employee DTO values as below,
 
Using Auto-Mapper in an ASP.NET Core MVC application
 
Using Auto-Mapper in an ASP.NET Core MVC application
 
Here we see that the empDTO object has the values extracted and mapped from the Employee object.
 

Summary

 
In this article, we looked at using the AutoMapper nuget package to easily transform classes from one structure to another. This is a common requirement in almost all applications when moving data from the user interface to the data store and vice versa. This process is made simple by using the technique explained in this article. Happy Coding!