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#.
  5. What will happen if the source and destination property names are different?
  6. How to map two properties when the names are different using automapper?
Why do we need AutoMapper in C#?

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

Why do we need AutoMapper in C#?

Now, if you want to copy the data or transfer the data from Employee object to the EmployeeDTO object, then in the traditional approach first you need to create and populate the Employee object as shown in the below image. 

Mapping Object in Traditional Approach

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

Mapping Object in Traditional Approach in C#

The complete example is given below. 

The following example, copy the data from one object to another object in the traditional approach i.e. without using the C# automapper.

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. Now if you run the application, then you will get the output 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 we can map two objects? Yes, there is, and 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. As we progress in this course, you will see the power of automapper.

How do I use AutoMapper in C#?

Let us understand how to use automapper in C# with a simple example using a console application. 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.

How do I use AutoMapper in C#?

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

Step1: Installing the AutoMapper library

The AutoMapper is an open-source library present in GitHub. To install this library, open the Package Manager Console window and then type the following command and press enter key to install the AutoMapper library in your project:

 PM> Install-Package AutoMapper

Once you installed the AutoMapper library, then it will add a reference to the AutoMapper dll which you can find the project references section as shown in the below image.

Installing the AutoMapper library

Once 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 simple 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.

Step2: Initializing or Configuring the AutoMapper

Once you have defines your types (i.e. classes) then you can create a mapper for the two types using the constructor of MapperConfiguration class. You can create only one MapperConfiguration instance per AppDomain and should be instantiated during the application start-up. The syntax to create the MapperConfiguration instance is given below.

AutoMapper in C#

The type on the left is the source type i.e. TSource, in our example, it will be going to Employee object, and the type on the right is the destination type i.e. TDestination, in our example, it will be going to EmployeeDTO object. So, two map the Employee with EmployeeDTO, you need to create the mapper configuration as shown below. 

Initializing or Configuring the AutoMapper

Using AutoMapper:

The following image shows how to initialize, and use automapper in C#. 

Using AutoMapper in C#

Below is the complete code
using System;
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Employee, EmployeeDTO>()
                );

            //Creating the source object
            Employee emp = new Employee
            {
                Name = "James",
                Salary = 20000,
                Address = "London",
                Department = "IT"
            };

            //Using automapper
            var mapper = new Mapper(config);
            var empDTO = mapper.Map<EmployeeDTO>(emp);
            //OR
            //var empDTO2 = mapper.Map<Employee, 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 you run the application, then it will display the data as expected.

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 object. 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 System;
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Employee, EmployeeDTO>()
                );

            //Creating the source object
            Employee emp = new Employee
            {
                Name = "James",
                Salary = 20000,
                Address = "London",
                Department = "IT"
            };

            //Using automapper
            var mapper = new Mapper(config);
            var empDTO = mapper.Map<EmployeeDTO>(emp);
            //OR
            //var empDTO2 = mapper.Map<Employee, 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; }
    }
}

With the above changes in place, now if you run the application, then you should get the following output.

What will happen if the source and destination property names are different?

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 C# Automapper will not map those properties

How to map two properties when the names are different using automapper?

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, you need to map these two properties in the mapping configuration as shown below.

How to map two properties when the names are different using automapper.

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

Below is the complete code.
using System;
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize the mapper
            var config = new MapperConfiguration(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))
                );

            //Creating the source object
            Employee emp = new Employee
            {
                Name = "James",
                Salary = 20000,
                Address = "London",
                Department = "IT"
            };

            //Using automapper
            var mapper = new Mapper(config);
            var empDTO = mapper.Map<EmployeeDTO>(emp);
            //OR
            //var empDTO2 = mapper.Map<Employee, 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 should 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 enjoy this article and understood the basics of C# AutoMapper.

12 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);

  2. I even cannot use the AutoMapper package.
    keep output this:
    error NU1108: Cycle detected.
    error NU1108: Automapper -> automapper (>= 8.1.1)

  3. Thank you. Very useful to get to get started with AutoMapper. I don’t think the static Mapper.Map method works anymore? Needs to be on object instance method now.

Leave a Reply

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