AutoMapper in C#

AutoMapper in C# with Examples

In this article, I am going to discuss AutoMapper in C# with some simple examples. At the end of this article, you will be having a very good understanding of the following pointers.

  1. Why do we need to use AutoMapper in C#?
  2. What is AutoMapper in C#?
  3. How do I use AutoMapper in C#?
  4. Multiple Examples to Understand AutoMapper in C#.
Why do we need AutoMapper in C#?

Let’s understand why we need auto mapper with an example. Let’s say we have two classes such as Employee and EmployeeDTO as shown in the below image.

AutoMapper in C#

If we want to copy the data or transfer the data from Employee class to EmployeeDTO class, then in the traditional approach first we need to create and populate the Employee object as shown below. 

Employee Onject

Once we have the employee object, then we need to create the EmployeeDTO object and need to copy the data from the employee object to employee DTO object as shown in the below image.

EmployeeDTO Object

The complete example is given below.

namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Name = "James";
            emp.Salary = 20000;
            emp.Address = "London";
            emp.Department = "IT";

            EmployeeDTO empDTO = new EmployeeDTO();
            empDTO.Name = emp.Name;
            empDTO.Salary = emp.Salary;
            empDTO.Address = emp.Address;
            empDTO.Department = emp.Department;

            Console.WriteLine("Name:" + empDTO.Name + ", Salary:" + empDTO.Salary + ", Address:" + empDTO.Address + ", Department:"+ empDTO.Department);
            Console.ReadLine();
        }
    }
    
    public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
    
    public class EmployeeDTO
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}
That’s it. It’s working as expected.

But, tomorrow what will you do if the data i.e. the properties in the class are increased. Then you need to write the code for each property data moving from the source class to the destination class. That means the Mapping of code is done again and again between the source and the destination.

In real-time projects, many times we need to map the objects between the UI/Domain or Service/Domain layers. Mapping the objects between them is very hectic using the traditional approach that we discussed in the above example. So, is there any simplest solution by which I can map two objects? Yes, there is, the solution is AutoMapper.

What is AutoMapper in C#?

The AutoMapper in C# is a mapper between two objects. That is AutoMapper is an object-object mapper. It maps the properties of two different objects by transforming the input object of one type to the output object of another type.

The AutoMapper also provides some interesting facts to take the dirty work out of figuring out how to map object of type A with an object of type B as long as the object of type B follows AutoMapper’s established convention.

How do I use AutoMapper in C#?

Let us understand this with an example. We are going to map the same Employee class with EmployeeDTO class that we discussed in the first example. We need to map each Employee properties to the correspondent EmployeeDTO properties using AutoMapper as shown in the below image.

AutoMapper in C-Sharp

Let’s discuss the step by step procedure to use AutoMapper in C#.

Installing the AutoMapper library

The AutoMapper is an open-source library present in GitHub. To install this library, open the Package Manager Console and enter the following command to install the AutoMapper library:

 PM> Install-Package AutoMapper

Once you installed the AutoMapper library,  then it will add a reference to the AutoMapper dll as shown in the below image within the References folder.

Installing Automapper DLLOnce you installed the Automapper in your project, then you can use it in many different ways. We will discuss all these options in a later article. In this article, I am going to discuss some examples to make you understand how exactly the AutoMapper works in a project.

We are going to work with the same example i.e. we are going to Map the Employee object with the EmployeeDTO object but here we are going to use AutoMapper.

Initialize or Configure the Mapper in C#:

Once you have defines your types then you can create a mapper for the two types using the MapperConfiguration or the static Mapper instance and the CreateMap method. You can create only one MapperConfiguration instance per AppDomain and should be instantiated during the application start-up. Alternatively, you can just use static Mapper.Initialize method.

Initializing AutoMapper

The type on the left is the source type i.e. TSource, in our example, it will be Employee, and the type on the right is the destination type i.e. TDestination, in our example, it will be EmployeeDTO as shown in the below image.

Initializing AutoMapper

Note: You need to use one option among the above two options.

It’s time to use the Mapper.

We can use the mapper in two different ways as shown below

AutoMapper in C-Sharp

Below is the complete code

First import the AutoMapper namespace

using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Step1: Initialize the mapper
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDTO>();
            });

            //Step2: Create the source object
            Employee emp = new Employee();
            emp.Name = "James";
            emp.Salary = 20000;
            emp.Address = "London";
            emp.Department = "IT";

            //Step3: use the mapper to map the source and destination object
            var empDTO = Mapper.Map<Employee, EmployeeDTO>(emp);
            //OR
            //var empDTO = Mapper.Map<EmployeeDTO>(emp);

            Console.WriteLine("Name:" + empDTO.Name + ", Salary:" + empDTO.Salary + ", Address:" + empDTO.Address + ", Department:" + empDTO.Department);
            Console.ReadLine();
        }
    }
    
    public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }

    public class EmployeeDTO
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}

When we run the application, it will display the data as expected. But what will happen if the source and destination property names are different? Let’s have a look by changing the property name of source and destination. Let’s change the EmployeeDTO class Name and Department property to FullName and Dept and run the application and see what happened.

Below is the complete example.
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Step1: Initialize the mapper
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDTO>();
            });

            //Step2: Create the source object
            Employee emp = new Employee();
            emp.Name = "James";
            emp.Salary = 20000;
            emp.Address = "London";
            emp.Department = "IT";

            //Step3: use the mapper to map the source and destination object
            var empDTO = Mapper.Map<Employee, EmployeeDTO>(emp);
            //OR
            //var empDTO = Mapper.Map<EmployeeDTO>(emp);

            Console.WriteLine("Name:" + empDTO.FullName + ", Salary:" + empDTO.Salary + ", Address:" + empDTO.Address + ", Department:" + empDTO.Dept);
            Console.ReadLine();
        }
    }
    
    public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }

    public class EmployeeDTO
    {
        public string FullName { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Dept { get; set; }
    }
}

Now run the application. It will display the following output.

AutoMapper in C-Sharp

From the above output, it clearly shows that the Name and Department are empty that means these two properties are not mapped from the Source type to the Destination type.

Note: When the property names are different in Source and Destination types, then by default the Automapper will not map those properties

Then the question comes to our mind is how to map two properties when the names are different?

The answer is by using ForMember option. So to the Map the Name property with the FullName property and the Department property with the Dept property we need to map these two in the mapping configuration as shown below.

AutoMapper in C-Sharp

We will discuss the ForMember and MapForm options in details in our upcoming articles.

Below is the complete code.
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Step1: Initialize the mapper

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Employee, EmployeeDTO>()
                    .ForMember(dest => dest.FullName, act => act.MapFrom(src => src.Name))
                    .ForMember(dest => dest.Dept, act => act.MapFrom(src => src.Department));
            });
            
            //Step2: Create the source object
            Employee emp = new Employee();
            emp.Name = "James";
            emp.Salary = 20000;
            emp.Address = "London";
            emp.Department = "IT";

            //Step3: use the mapper to map the source and destination object
            var empDTO = Mapper.Map<Employee, EmployeeDTO>(emp);
            //OR
            //var empDTO = Mapper.Map<EmployeeDTO>(emp);

            Console.WriteLine("Name:" + empDTO.FullName + ", Salary:" + empDTO.Salary + ", Address:" + empDTO.Address + ", Department:" + empDTO.Dept);
            Console.ReadLine();
        }
    }
    
    public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }

    public class EmployeeDTO
    {
        public string FullName { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Dept { get; set; }
    }
}

Now run the application and you will see the output as expected. In the next article, I am going to discuss the Automapper Complex Mapping in C# with examples. In this article, I try to explain AutoMapper in C# with some examples. I hope you understood the basics of AutoMapper.

3 thoughts on “AutoMapper in C#”

  1. Hi this is not working for framework 4.6.1
    var empDTO = Mapper.Map(emp);

    I tried the below code woked for me well
    var config = new MapperConfiguration(cfg => cfg.CreateMap()
    );
    IMapper imap = config.CreateMapper();
    EmployeeData data = new EmployeeData();
    data.Name = “James”;
    data.Salary = 200000;
    data.Address = “London”;
    data.Department = “IT”;
    var destination = imap.Map(data);
    Console.WriteLine(destination.Name);

Leave a Reply

Your email address will not be published. Required fields are marked *