AutoMapper in C#

AutoMapper in C# with Examples

In this article, I am going to discuss AutoMapper in C# with 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 we need Automapper in C# with an example. Let’s say we have the following two classes Employee and EmployeeDTO. First, create a class file with the name Employee.cs and then copy and paste the following code into it. This is a very simple class having 4 properties.

namespace AutoMapperDemo
{
    public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}

Next, create another class file with the name EmployeeDTO.cs and then copy and paste the following code into it. This class is identical to the Employee class i.e. having 4 properties.

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

Now, what is our business requirement is to copy the data or transfer the data from the Employee object to the EmployeeDTO object. In the traditional approach (without using Automapper), first, we 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 you need to copy the data from the Employee object to the EmployeeDTO object as shown in the below image.

Mapping Object in Traditional Approach in C#

Mapping Object in Traditional Approach in C#

Let us understand how the Object is Mapped to another Object in C# using Traditional Approach. For a better understanding, please have a look at the following example. Here, first, we create an instance of the Employee object and populate the four properties with the required data. Then we create an instance of EmployeeDTO class and populate the EmployeeDTO properties with the values from the Employee object. Finally, we displayed the values of the EmployeeDTO object.

using System;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create and Populate Employee Object
            Employee emp = new Employee
            {
                Name = "James",
                Salary = 20000,
                Address = "London",
                Department = "IT"
            };

            //Mapping Employee Object to EmployeeDTO Object
            EmployeeDTO empDTO = new EmployeeDTO
            {
                Name = emp.Name,
                Salary = emp.Salary,
                Address = emp.Address,
                Department = emp.Department
            };

            Console.WriteLine("Name:" + empDTO.Name + ", Salary:" + empDTO.Salary + ", Address:" + empDTO.Address + ", Department:" + empDTO.Department);
            Console.ReadLine();
        }
    }
}

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 Employee and EmployeeDTO classes are increased? Then you need to write the data moving code for each property 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. And again, if the same mapping is at different places, then you need to do the changes at different places, which is not only time-consuming but also error-prone.

In Real-Time Projects, many times we need to map the objects between the UI Layer or Presentation Layer and Business Logic 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. If this is not clear at the moment, don’t worry once we see the example, then you will clearly understand this concept.

AutoMapper also provides some interesting facts to take the dirty work out of figuring out how to map an object of type A with an object of type B as long as the object of type B follows AutoMapper’s Default Convention i.e. AutoMapper Default Rules. As we progress in this course, you will see the power of AutoMapper.

How to use AutoMapper in C#?

Let us understand how to use AutoMapper in C# with an example. We are going to map the same Employee Object with EmployeeDTO Object that we discussed in the first example. We need to map each Employee Property to the corresponding EmployeeDTO Properties using AutoMapper as shown in the below image.

How to use AutoMapper in C#

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

Step 1: Installing AutoMapper Library in Your Project

AutoMapper is an open-source library present in GitHub. To install this library, open the Package Manager Console window. To Open the Package Manager Console window, select Tools => NuGet Package Manager => Package Manager Console from the context menu as shown in the below image.

Installing AutoMapper Library

Once you open the Package Manager Console window, then type the command Install-Package AutoMapper, and press enter key to install the AutoMapper Library in your project as shown in the below image.

Install-Package AutoMapper

Note: If you are getting any errors while installing AutoMapper, then try to install the lower version of the AutoMapper which is compatible with your .NET Framework Version. I am working with .NET Framework 4.8 and I am installing AutoMapper 10.1.1 version which is compatible with .NET Framework 4.8.

Once you installed the AutoMapper Library in your project, then it will add a reference to the AutoMapper.DLL which you can find in 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 your project 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 AutoMapper works in C#. 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: Configuring and Initializing AutoMapper in C#

In the second step, we need to configure and Initialize the AutoMapper for our project. Once we have defines the types (i.e. classes to be mapped by AutoMapper, in our example once we define the Employee and EmployeeDTO classes), then need to configure the Mapping for the two types using the constructor of MapperConfiguration class. The point that you need to remember is 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. Here, we need to provide the Mapper Configuration using Lambda Expression and also we need to tell the Source and Destination types.

AutoMapper in C# with Examples

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

AutoMapper in C# with Examples

Once we create the MapperConfiguration instance where we configure all the Mappings, then we need to initialize the Mapper. To Initialize the Mapper, what we need to do is, we just need to pass the MapperConfiguration to the constructor of the Mapper class as shown in the below image.

Configuring and Initializing AutoMapper in C#

So, what we are going to do is, we will create a separate class where we will do all our mapping configurations. So, create a class file with the name MapperConfig.cs and then copy and paste the following code into it. In the below class, we are having one method which is to configure the required mappings as well as initialize the Mapper. We are also returning the Mapper instance using which we will do the mapping. Here we are using the CreateMap generic method and specifying the Source and Destination Types. Here, the Source Type is Employee, and Destination Type is EmployeeDTO i.e. we are going to map the Employee Object with the EmployeeDTO object using AutoMapper.

using AutoMapper;
namespace AutoMapperDemo
{
    public class MapperConfig
    {
        public static Mapper InitializeAutomapper()
        {
            //Provide all the Mapping Configuration
            var config = new MapperConfiguration(cfg =>
            {
                    //Configuring Employee and EmployeeDTO
                    cfg.CreateMap<Employee, EmployeeDTO>();
                    //Any Other Mapping Configuration ....
                });

            //Create an Instance of Mapper and return that Instance
            var mapper = new Mapper(config);
            return mapper;
        }
    }
}
Step 3: Using AutoMapper in C#:

Once we have Configured the Mapping Configurations i.e. configuring the Source and Destination Types, then we can use that Mapping Configuration to Map the Source and Destination Objects. For this, we need to use the Mapper instance which is created in the previous step. So, we need to call the InitializeAutomapper static method using the MapperConfig class name which will return the Mapper instance. Once we have the Mapper instance, then using the Map method of the Mapper instance, we can provide the Source object and the Destination Object in two ways which are shown in the below image.

Using AutoMapper in C#

For a better understanding, modify the Main method of the Program class as follows. Here, we are Mapping the Source Employee Object with the Destination EmployeeDTO object using AutoMapper in C#. The following Example code is self-explained, so please go through the comment lines.

using System;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create and Populate Employee Object i.e. Source Object
            Employee emp = new Employee
            {
                Name = "James",
                Salary = 20000,
                Address = "London",
                Department = "IT"
            };
            
            //Initializing AutoMapper
            var mapper = MapperConfig.InitializeAutomapper();

            //Way1: Specify the Destination Type and to The Map Method pass the Source Object
            //Now, empDTO1 object will having the same values as emp object
            var empDTO1 = mapper.Map<EmployeeDTO>(emp);
            
            //Way2: Specify the both Source and Destination Type 
            //and to The Map Method pass the Source Object
            //Now, empDTO2 object will having the same values as emp object
            var empDTO2 = mapper.Map<Employee, EmployeeDTO>(emp);

            Console.WriteLine("Name: " + empDTO1.Name + ", Salary: " + empDTO1.Salary + ", Address: " + empDTO1.Address + ", Department: " + empDTO1.Department);
            Console.ReadLine();
        }
    }
}

Output: Name: James, Salary: 20000, Address: London, Department: IT

What will happen if the Source and Destination Property Names are Different?

Let us understand this with an example. Let us change the property names of the Destination class. Let’s change the EmployeeDTO class property names. Change the Name property to FullName and Department property to Dept. So, modify the EmployeeDTO class as follows.

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

Next, modify the Main method of the Program class as follows to use the new property names while displaying the values.

using System;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create and Populate Employee Object i.e. Source Object
            Employee emp = new Employee
            {
                Name = "James",
                Salary = 20000,
                Address = "London",
                Department = "IT"
            };
            
            //Initializing AutoMapper
            var mapper = MapperConfig.InitializeAutomapper();

            //Way1: Specify the Destination Type and to The Map Method pass the Source Object
            //Now, empDTO1 object will having the same values as emp object
            var empDTO1 = mapper.Map<EmployeeDTO>(emp);
            
            //Way2: Specify the both Source and Destination Type 
            //and to The Map Method pass the Source Object
            //Now, empDTO2 object will having the same values as emp object
            var empDTO2 = mapper.Map<Employee, EmployeeDTO>(emp);

            Console.WriteLine("Name:" + empDTO1.FullName + ", Salary:" + empDTO1.Salary + ", Address:" + empDTO1.Address + ", Department:" + empDTO1.Dept);
            Console.ReadLine();
        }
    }
}

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

AutoMapper in C# with Examples

The above output clearly shows that the Name and Department are empty which means these two properties are not mapped from the Source type to the Destination type. So, the point that you need to remember is when the property names are different in Source and Destination types, then by default, Automapper will not map those properties from the source object to the destination object.

How do Map Properties when the Property Names are Different using AutoMapper?

If the Property names are different in Source and Destination types, then you can map such properties in AutoMapper by using the ForMember option. So, to Map the Name property of the Source Object with the FullName property of the Destination Object and the Department property of the Source Object with the Dept property of the Destination Object, we need to provide mapping configuration for these two properties in the mapping configuration. So, modify the MapperConfig class file as follows to provide such property mapping configurations. We will discuss the ForMember and MapForm options in detail in our upcoming articles.

using AutoMapper;
namespace AutoMapperDemo
{
    public class MapperConfig
    {
        public static Mapper InitializeAutomapper()
        {
            //Provide all the Mapping Configuration
            var config = new MapperConfiguration(cfg =>
            {
                //Configuring Employee and EmployeeDTO
                cfg.CreateMap<Employee, EmployeeDTO>()

                //Provide Mapping Configuration of FullName and Name Property
                .ForMember(dest => dest.FullName, act => act.MapFrom(src => src.Name))
                
                //Provide Mapping Dept of FullName and Department Property
                .ForMember(dest => dest.Dept, act => act.MapFrom(src => src.Department));

                //Any Other Mapping Configuration ....
            });

            //Create an Instance of Mapper and return that Instance
            var mapper = new Mapper(config);
            return mapper;
        }
    }
}

With the above changes in place, now run the application and you should see the output as expected.

In the next article, I am going to discuss Automapper Complex Mapping in C# with Examples. In this article, I try to explain AutoMapper in C# with Examples. I hope you enjoy this AutoMapper in C# with Examples article.

15 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.

  4. What world happen when you only want to Automap and for example the Department is let out.:
    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; }

    }

Leave a Reply

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