Some Useful Tips While Using Automapper In C#

In my previous article on Using AutoMapper In MVC Project, I described the following things.
  1. What is Automapper.
  2. How to use Automapper in MVC project.
  3.  Some Basic Advantages of Automapper.
In this article I would like to go deep inside the automapper. Before starting my article let me explain the Automapper once again.

"AutoMapper is an object-object mapper which allows you to solve the problem of manually mapping each property of a class with the same properties of another class.".

Before AutoMapper was introduced if we wanted to assign one object property to another object property then we were following a long procedure. We had to map each property of these two different objects. Suppose in one class we have 30 properties and we want to map this with another class having 30 properties, then we would have to map this property one-by-one 30 times. Thus for this problem, a new concept, AutoMapper, was introduced.

The main demerit of using automapper mapping is that it needs the two different class property name to be the same, otherwise it fails to map automatically, and again we have to map them manually.

Here I am giving one example.

Consider we have 2 classes, User.cs and Patient.cs, and we need user property to be mapped with Patient property as shown below.

As per the automapper rule it will map to those properties whose names are the same. So I am marking here which of them are mapped by automapper.

Those properties which are not mapped automatically due to violatio of the automapper rule we can map them manually. So our first goal is to see how we can map these properties manually.

Here I am creating a console application with same 2 classes in a console project.

To use automapper goto the Nuget Package Manager and install Automapper.


So to map them manually we need to  specify the member like this. Let's check the problem first.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using AutoMapper;  
  7. namespace Mapper  
  8. {  
  9.     public class User  
  10.     {  
  11.         public int ID { getset; }  
  12.         public string Name { getset; }  
  13.         public string Email { getset; }  
  14.         public string Address { getset; }  
  15.         public string Company { getset; }  
  16.         public string FatherName { getset; }  
  17.         public string Dept { getset; }  
  18.         public string Gender { getset; }  
  19.         public string maritialstatus { getset; }  
  20.     }  
  21.     public class Patient  
  22.     {  
  23.          public int PatientID { getset; }  
  24.         public string Name { getset; }  
  25.         public string Email { getset; }  
  26.         public string Address { getset; }  
  27.         public string Job { getset; }  
  28.         public string FatherName { getset; }  
  29.         public string salary { getset; }  
  30.         public string Gender { getset; }  
  31.         public string maritialstatus { getset; }  
  32.   
  33.     }  
  34.      public class Demo  
  35.      {  
  36.   
  37.         static void Main(string[] args)  
  38.         {  
  39.             User uobj = new User();  
  40.             uobj.ID = 100;  
  41.             uobj.Name = "Susant";  
  42.             uobj.Address = "Bangalore";  
  43.             uobj.Company = "Accenture";  
  44.             uobj.Dept = "IT";  
  45.             uobj.Dept = "[email protected]";  
  46.             uobj.FatherName = "Mohan";  
  47.             uobj.Gender = "Male";  
  48.             uobj.maritialstatus = "Unmarried";  
  49.              
  50.   
  51.            AutoMapper.Mapper.CreateMap<User, Patient>();  
  52.             
  53.   
  54.             var mappeddata = AutoMapper.Mapper.Map<User,Patient>(uobj);  
  55.   
  56.             Console.WriteLine(mappeddata.PatientID + Environment.NewLine +  
  57.                 mappeddata.Name + Environment.NewLine +  
  58.                 mappeddata.Address + Environment.NewLine+  
  59.                 mappeddata.Job + Environment.NewLine+  
  60.                 mappeddata.FatherName + Environment.NewLine +  
  61.                  mappeddata.Gender + Environment.NewLine +  
  62.                  mappeddata.maritialstatus+Environment.NewLine   
  63.                 );  
  64.             Console.ReadLine();  
  65.   
  66.         }  
  67.     }  
  68. }  
As it is not mapped it gives the following output.


Now let's try to map these members manually.

We can map manually using the keyword "ForMember" like this.
  1. AutoMapper.Mapper.CreateMap<User, Patient>().ForMember(dest => dest.PatientID, opt => opt.MapFrom(src => src.ID))  
  2.   
  3.                .ForMember(dest => dest.Job, opt => opt.MapFrom(src => src.Company)  
  4.   
  5.                );  
  6.   
  7.   
  8.            var mappeddata = AutoMapper.Mapper.Map<User,Patient>(uobj);  
Here  we are manually mapping patientId with Id and Job with Company. 

After that just print the data as follow and check the Output.
  1. Console.WriteLine(mappeddata.PatientID + Environment.NewLine +  
  2.                mappeddata.Name + Environment.NewLine +  
  3.                mappeddata.Address + Environment.NewLine+  
  4.                mappeddata.Job + Environment.NewLine+  
  5.                mappeddata.FatherName + Environment.NewLine +  
  6.                 mappeddata.Gender + Environment.NewLine +  
  7.                 mappeddata.maritialstatus+Environment.NewLine   
  8.                );  
Here is the mapped out put produced.

So in this way we can map each property with another if the name mismatch.

Mapping Based On Condition:

In automapper we can map 2 properties based on condition also. As we look in my above example i have assigned Id property to 100. Now i am putting a condition here i will map the name if id==100 other wise i will not map.So for this  let check the code.
  1. AutoMapper.Mapper.CreateMap<User, Patient>()  
  2.  .ForMember(dest => dest.Name,opt => opt.Condition(src=>((User)src.Parent.SourceValue).ID ==100));  
This will print the result as we want like this.



Now let me change the condition which is False,it will not print anything  as shown below.
  1. AutoMapper.Mapper.CreateMap<User, Patient>()  
  2.  .ForMember(dest => dest.Name,opt => opt.Condition(src=>((User)src.Parent.SourceValue).ID ==10));  


So in this way we can see how we can map with condition.
 
Read more articles on C#:


Similar Articles