Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

Many time we need to map objects between UI/Domain or Service/Domain layers. Mapping the objects between them is very hectic. So, are there any simplest mechanism by which I can map two objects? Is there is.

 

There is a AutoMapper class which you can use to map between two objects. This also provides option to do a custom mapping. Let’s begin with it and learn about it today.

 

What is AutoMapper?

AutoMapper is a mapper between two objects. It maps two different entities by transforming an input object of one type to an output object of another type. It is very tough job to map two different entities and sometime it is even more hectic when it comes to testing. It can be anywhere in the application but in general it happens in UI/Domain or Service/Domain layers.

 

 

What is AutoMapper and How to map two objects using AutoMapper?

 

AutoMapper resolves that tough job by mapping it with proper convention and removes all the dirty works. Not only that, you can also customize the mapping with proper parameters.

 

How to Download AutoMapper?

AutoMapper is a open source library present in GitHub. To install the library, first install the NuGet Package Manager in your Visual Studio IDE. Once you installed the NuGet package manager, open the NuGet console and enter the following command to install the AutoMapper library:

 

PM>  Install-Package AutoMapper

 

Once installed, verify the installation from your Visual Studio. If your project is open inside Visual Studio, it will automatically add the reference of the dll to the project.

 

How to Map two objects using AutoMapper?

AutoMapper can be used in a project many ways. Visit the “Getting Started” for further details. Here in this post, I will cover a basic sample to make you understand about the library and how to use that in your project.

 

Let’s begin with a console application and create two class named “Person” and “Employee”. Those two different entities have few properties in common but the Employee class will have an extra property.

 

 

In the below code snippet, you can see that, the Person class has four properties named Firstname, Lastname, Address and Contact. But Employee class has additional property named Fullname along with other properties.

What is AutoMapper and How to map two objects using AutoMapper?

 

Now suppose, as per requirement we have to map these two entities in our project. I assume, you already installed the assembly reference of the library in your project. For the use of this demo, we will override the ToString() method of the Employee class so that when we call the ToString() method to the object, it returns the values of it’s properties in proper manner.

 

Here is the complete code snippet of the same for your reference:

public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Address { get; set; }
    public int Contact { get; set; }
}
 
public class Employee
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Fullname { get; set; }
    public string Address { get; set; }
    public int Contact { get; set; }
 
    // just overriding the ToString() method for simplicity
    public override string ToString()
    {
        return "Firstname: " + Firstname + Environment.NewLine +
               "Lastname: " + Lastname + Environment.NewLine +
               "Fullname: " + Fullname + Environment.NewLine +
               "Address: " + Address + Environment.NewLine +
               "Contact: " + Contact + Environment.NewLine;
    }
}

 

Let’s start with default mapping. In this case, we will map the two entities without providing additional parameters to it. The mapping will automatically map it’s properties based on the names of them. So in this case, it will have mappings between Firstname, Lastname, Address and Contact. As the Fullname property of Employee class does not have equivalent property in the Person class, it will not be mapped.

 

 

To create the default mapping, call the Mapper.CreateMap<T1, T2>() with proper types. In this case, T1 will be Person and T2 will be Employee. Check out the below code snippet for quick reference:

    // create the mapping between two object types "Person" and "Employee"
Mapper.CreateMap<Person, Employee>();
 
// create the instance of Person with proper details
var person = new Person
{
    Firstname = "Kunal", Lastname = "Chowdhury",
    Address = "Tripura", Contact = 1234567890
};
 
// get the mapped instance of Person as Employee
var employee = Mapper.Map<Person, Employee>(person);
 
Console.WriteLine(employee.ToString());

 

 

Finally call the Mapper.Map<T1, T2>(obj1) to get the mapped object of T2. Now when you print the object of Employee, you will see that it mapped all the properties except Fullname. We will see the output later in this post.

 

 

Now let’s do a little more complex operation. Here we will create a custom mappings between two objects Person and Employee. The ForMemer() and MapFrom() extensions do the same for you as mentioned in the below code snippet:

 

// create custom mapping between two object types "Person" and "Employee"
Mapper.CreateMap<Person, Employee>().ForMember(emp => emp.Fullname, 
                            map => map.MapFrom(p => p.Firstname + " " + p.Lastname));
 
// create the instance of Person with proper details
person = new Person
{
    Firstname = "Kunal", Lastname = "Chowdhury",
    Address = "Tripura", Contact = 1234567890
};
 
// get the mapped instance of Person as Employee
employee = Mapper.Map<Person, Employee>(person);
 
Console.WriteLine(employee.ToString());

 

 

Here in this case, it will map the equivalent properties of the both class and in addition to that, it will also map the Fullname property of the Employee class with the concatenated string of Firstname and Lastname properties as mentioned in the conditional parameter above. So now when you print the object of Employee, you will see the Fullname property automatically populated with Firstname and Lastname.

 

Here is the output of the above two code examples (both default mapping and custom mapping):

Auto Mapping Output (default and custom)

 

 

I hope, this post will be a great help for you to create basic mappings between two entities whether it is in the client side or server side. To know more about the AutoMapper class and it’s usage in various complex scenarios, check out the following Wiki pages of the project in GitHub:

Do you have further queries on this? Do let me know below and I will try to help you as soon as I can. Connect with me for technical queries and updates on various news, articles. Don’t forget to share this post to your network and leave a comment below if that helps you. Have a great day. Cheers.

Have a question? Or, a comment? Let's Discuss it below...

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.