Getting Started With Automapper In .NET Core

Automapper is one of the most widely adopted Object-To-Object Mappers that reduces a lot of the pain of developers. The purpose of Mapper is to reduce the amount of repeated code that a developer needs to write when assigning values from one Object To another. With much less configuration you can be up and running. Whenever we are creating applications, we have multiple layers. These multiple layers have different separation of concerns. To handle those separations of concern we have to create multiple entities that contain repeated multiple properties. In each layer we exclude those properties that should not be exposed to other layers due to security concerns or separation of concerns. Let's see what it means!!
 
Example
 
In Data Access Layer,
  1. public class Person {  
  2.     public string Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public DateTime DateOfBirth {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string Username {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string Password {  
  19.         get;  
  20.         set;  
  21.     }  
  22. }  
In Service Layer,
  1. public class PersonRequest {  
  2.     public string Username {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Password {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
  11. public class PersonResponse {  
  12.     public string Name {  
  13.         get;  
  14.         set;  
  15.     }  
  16.     public int Age {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     public string Username {  
  21.         get;  
  22.         set;  
  23.     }  
  24. }  
We have to perform mapping like this,
 
PersonRequest → Person
 
Person → PersonResponse
 
In Normal scenario we do like this,
 
For request handling,
  1. PersonRequest request = new PersonRequest();      
  2. request.Username = “varun”;      
  3. request.Password = ”Te$t”;      
  4. Person person = new Person();      
  5. person.Username = request.Username;      
  6. person.Password = request.Password;    
Now this Person type class is handled in DataAccess Layer inside a method to make a Login Call with a Parameter of Type Person. After the login call to the database we got the response. Now it's a lot of work to get only essential fields in the response,
  1. //Data Access Method Representation     
  2. public Person Login(Person request){    
  3.     //..Implementation to Login and return value    
  4. }  
To get only essential fields in response, it';s a lot of work:
  1. Person person = new DataAccess().Login(personEntity);  
  2. PersonResponse response = new PersonResponse();    
  3. response.Name = person.Name;    
  4.     
  5. //…….   
Lots of extra code will be required, and imagine these were 50 fields. No, we don’t need that much manual work to waste our time. This is a small example with limited properties, in real life we can have more than 20 properties, 50 or more depending upon the complexity. To overcome such issues we have Object-Object Mappers.Then automapper is a timesaver. Now, let us see a practical  automapper example along with configuration,
 
Pre-Requisites
 
To install package,
 
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
 
Namespace to Include,
 
using Automapper;
 
Code
 
Creating Mapping Profiles - Profiles are the best way to organize mapping
  1. public class ReqResToEntityProfile: Profile {  
  2.     public ReqResToEntityProfile() {  
  3.         CreateMap < Person, PersonResponse > ();  
  4.         CreateMap < PersonRequest, Person > ();  
  5.     }  
  6. }  
Code Configuration - In this example we are using Dependency Injection feature of .NET Core.
  1. // This method gets called by the runtime. Use this method to add services to the container.    
  2. public void ConfigureServices(IServiceCollection services)    
  3. {    
  4.    services.AddAutoMapper(typeof(ReqResToEntityProfile));    
  5. //...   
Invoking in Application,
  1. namespace Automapper.App.Controllers    
  2. {    
  3.     public class HomeController : Controller    
  4.     {    
  5.         private readonly ILogger<HomeController> _logger;    
  6.         private IMapper mapper;    
  7.         public HomeController(ILogger<HomeController> logger,IMapper mapper)    
  8.         {    
  9.             _logger = logger;    
  10.             this.mapper = mapper;    
  11.         }    
  12.     
  13.         public IActionResult Index()    
  14.         {    
  15.             var peoplesData = InMemoryData.Data.GetPeople();    
  16.             var response = mapper.Map<List<PersonResponse>>(peoplesData);    
  17.             return Ok(response);    
  18.         }    
  19. //....  
Result
 
  1. [{"name":"Varun","age":0,"username":"varun"},{"name":"John","age":0,"username":"john2"},{"name":"Megan","age":0,"username":"megan3"}]  
Now, in the phase of mapping we have lost the conversion of DateOfBirth To Age. Let us find a solution for that.
 
For this purpose we will do some changes. New changes will look like this,
  1. public ReqResToEntityProfile()    
  2. {    
  3.     CreateMap<Person,PersonResponse>()    
  4.     .ForMember(d=>d.Age,o=>o.MapFrom(s => DateTime.Now.Subtract(s.DateOfBirth).Days/365 ));    
  5.     CreateMap<PersonRequest,Person>();    
  6. }   
Result
  1. [{"name":"Varun","age":40,"username":"varun"},{"name":"John","age":30,"username":"john2"},{"name":"Megan","age":25,"username":"megan3"}]  
Similar to this, we will transform Request Object To Person Object,
  1. public IActionResult RequestSample() {  
  2.     var peoplesData = InMemoryData.Data.GetPersonRequest();  
  3.     var request = mapper.Map < Person > (peoplesData);  
  4.     return Ok(request);  
  5. }  
Result
  1. {"id":null,"name":null,"dateOfBirth":"0001-01-01T00:00:00","username":"varun","password":"te$t"}   
That's it!! 
 
Extra Notes
 
Creating Application using .NET Core CLI,
 
dotnet new sln
dotnet new mvc -o "Automapper.App" -f netcoreapp3.1
dotnet sln add Automapper.App/Automapper.App.csproj
cd Automapper.App
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
 
Sample Data Class,
  1. namespace Automapper.App.InMemoryData {  
  2.     public class Data {  
  3.         public static List < Person > GetPeople() {  
  4.             List < Person > persons = new List < Person > {  
  5.                 new Person {  
  6.                     Id = "1", Name = "Varun", DateOfBirth = new DateTime(1980, 1, 1), Password = "te$t", Username = "varun"  
  7.                 },  
  8.                 new Person {  
  9.                     Id = "2", Name = "John", DateOfBirth = new DateTime(1990, 1, 1), Password = "te$ta", Username = "john2"  
  10.                 },  
  11.                 new Person {  
  12.                     Id = "3", Name = "Megan", DateOfBirth = new DateTime(1995, 1, 1), Password = "te$tx", Username = "megan3"  
  13.                 }  
  14.             };  
  15.             return persons;  
  16.         }  
  17.         public static PersonRequest GetPersonRequest() {  
  18.             PersonRequest request = new PersonRequest {  
  19.                 Username = "varun",  
  20.                     Password = "te$t"  
  21.             };  
  22.             return request;  
  23.         }  
  24.     }  
  25. }   
That's It! Thank you for reading. Source Code is available as an attachment. You can comment for suggestions and improvements.