Automapper Tutorial

The Automapper is a mapping or mapper between two objects, or you can consider it an object-object mapper. It is an excellent feature that helps map the different properties of two objects by converting an input object of one particular type to the output object of another type. The Automapper is considered to be one of the important concepts in C#.

Automapper Tutorial

Why use AutoMapper C#?

AutoMapper is an excellent feature that provides you a wonderful opportunity to provide a few configurations of mapping between two objects of different types that helps to lead to the segregated models and can affect the object types in that particular layer in case of multilayer scenarios and can help you to avoid the conflict.

Behind The Scenes

Behind the scenes, Automapper uses the programming concept called Reflection that helps you to get the type of object from an existing object dynamically, and that helps to access its properties easily.

How do I use AutoMapper C#?

To work with the Automapper, we first need the object type of the source and destination. Automapper best fits in the scenario where, for example, you have a member in the source named “Address.” This will be mapped automatically with the name “Address”.

It’s always better to keep the source and destination object names the same while using the Automapper.

Another good thing is Auto mapper will ignore the null reference exceptions when it maps the source object with the object of your destination.

How to work with AutoMapper

Let’s consider we have two objects, Students and StudentsDTO. We will map the Students’ properties with the StudentDTO’s properties.

public class Students
    {
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }
public class StudentsDTO
    {
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }

Below are the steps we need to follow to work with the Automapper.

Installation of the AutoMapper library

The first step is to install the automapper library to use the automapper feature in your application. You can easily do the installation using the Nuget Package Manager Console window. We have already discussed the installation. Check out the Automapper installation here.

Configuring the AutoMapper C#

Once you have installed the Automappaer library and the types are ready, we can configure the automapper using the MapperConfiguration class. One important point is that we can create only one instance of the MapperConfiguration class per the App domain.

Below is the syntax to create the instance of the MapperConfiguration class.

var config = new MapperConfiguration(cfg => cfg.CreateMap<source, Destination>());

If we consider the Students and StudentsDTO class, the syntax will be like the below

var config = new MapperConfiguration(cfg => cfg.CreateMap<Students, StudentsDTO>());

Using AutoMapper C#

Now, let’s see, using the AutoMapper C#, how it will be

Create mappings using AutoMapper

var myconfig = new MapperConfiguration(cfg => cfg.CreateMap<source, Destination>());

var mapper = myconfig.CreateMapper();
// or
var mapper = new Mapper(myconfig);
StudentsDTO dto = mapper.Map<StudentsDTO>(Students);

Where to configure AutoMapper?

As discussed above, you should do the Automapper configuration once per app domain and keep the Automapper configuration code in the startup class. For example, if you consider an ASP.net application, then it should be Global.asax file.

What if the source and destination property names are different?

It is always a best practice to keep the property name the same in source and destination if you want to implement the Automapper feature. At the same time, if the name of the properties in the source differs from the name of the properties in the destination, it is also possible to implement the Automapper feature.

When the names are different how to use automapper?

An easy way to implement the Automapper feature in the scenario is when the name of the properties in the source differs from the name in the destination—forMember option.

For an example, consider the below Students and StudentDTO class

public class Students
    {
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }

and the StudentDTO class is as below

public class StudentsDTO
    {
        public string FName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
    }

This example shows that the first property name in the Students(Source) class is FirstName, and in the StudentsDTO(Destination) class is FName. If we implement the Automapper feature in this scenario, the implementation will be like below.

 //Initializing the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Students, StudentsDTO>()
                    .ForMember(dest => dest.FName, act => act.MapFrom(src => src.FirstName))

This is how to do Mapping to Properties with different Names.

AutoMapper Examples

Let’s see an example of the Automapper with the actual value. Let’s take the same example of the Students

using System;
using AutoMapper;
namespace TestAutoMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initializing the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Students, StudentsDTO>()
                    .ForMember(dest => dest.FName, act => act.MapFrom(src => src.FirstName)

            //Instanciating the source
            Students st = new Students
            {
                FirstName
 = "Rajkishore",
                LastName
 = "Sahoo"
              
            };

            //Use automapper
            var mapper = new Mapper(config);
            var stDTO = mapper.Map<StudentsDTO>(st);
            //OR
            //var stDTO2 = mapper.Map<Students, StudentsDTO>(st);

            Console.WriteLine("FirstName:" + stDTO.FirstName + ", LatName:" + stDTO.Salary);
            Console.ReadLine();
        }
    }
    
    public class Students
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
    }

    public class StudentsDTO
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

When the Property names are different

using System;
using AutoMapper;
namespace TestAutoMapper
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initializing the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Students, StudentsDTO>()
                );

            //Instanciating the source
            Students st = new Students
            {
                FirstName
 = "Rajkishore",
                LastName
 = "Sahoo"
              
            };

            //Use automapper
            var mapper = new Mapper(config);
            var stDTO = mapper.Map<StudentsDTO>(st);
            //OR
            //var stDTO2 = mapper.Map<Students, StudentsDTO>(st);

            Console.WriteLine("FirstName:" + stDTO.FirstName + ", LatName:" + stDTO.Salary);
            Console.ReadLine();
        }
    }
    
    public class Students
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
    }

    public class StudentsDTO
    {
        public string FName { get; set; }
        public string LastName { get; set; }
    }
}

How to use projections in AutoMapper?

When we are discussing the Projections here, that means when the structure of the source is different than the structure of the destination. No worries. Automapper has great support for this scenario. Let’s see an example of the implementation.

public class EmployeeAddress
    {
        public string State { get; set; }
        public string Country { get; set; }
    }

The Employee class looks like below.

public class Employee
    {
        public int EmpId
        {
            get; set;
        }
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
        public EmployeeAddress EmployeeAddress

        {
            get; set;
        }
    }

The EmployeeDTO class looks like the below

public class Employee
    {
        public int EmpId
        {
            get; set;
        }
        public string FirstName
        {
            get;set;
        }
        public string LastName
        {
            get; set;
        }
       public string State { get; set; }
       public string Country { get; set; }
    }

The implementation of the Automapper will be like below

var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<EmployeeDTO, Employee>()
                   .ForMember(destination => destination.EmployeeAddress,
              map => map.MapFrom(
                  source => new EmployeeAddress
                  {
                      State = source .State,
                      Country = source.Country
                  }));

Best Practices AutoMapper

Below are a few best practices that are recommended

  1. If possible, it is better to avoid calling the CreateMap() on each request. Do it once in the StartUp class.
  2. Try avoiding the inline mappings wherever possible.
  3. If the mapping is complex, it is better not to use the Automapper feature.

You may also like following the articles below

Conclusion

In this article, we discussed a complete end-to-end tutorial on AutoMapper. Thanks for reading this article !!!