Efficient Data Copying with AutoMapper in C#

This article provides some guidelines on how to use AutoMapper in C#.

We have come across a lot of situations when we need to copy data from one object to another. Normally, we follow the below-mentioned approach to achieve this. Let’s say we have two classes declared as below,

First Class

public class UserObject   
    public int Id;   
    public string Name;   
    public string Address;   

Second Class

public class UserAnotherObject
    public int Id;
    public string Name;
    public string Address;

Now, if an object of the first class has some data in it and we want to copy that data to an object of the second class, we would be using the following approach for this.

UserObject uObj = new UserObject();                     // an object of First Class
UserAnotherObject uAnotherObj = new UserAnotherObject(); // an object of Second

uAnotherObj.Id = uObj.Id;
uAnotherObj.Name = uObj.Name;
uAnotherObj.Address = uObj.Address;

This is undoubtedly a tedious and repetitive task in case the object has a lot of properties.

Now, to overcome this task we can use a Nuget Package called the Auto-Mapper. Its working is quite simple to explain, in that it creates a copy of one object into another but a bit automatically on the basis of Datatypes and names of the properties.

In order to use AutoMapper we would have to install it first from the Nuget Package Manager as pictorially explained below.

Step 1. Go to the Manage NuGet Packages option in the project.

NuGet Packages

Step 2. Search and install AutoMapper to your project.


Step 3. Include the required Library on the page.

using AutoMapper.Mappers;

Now that this has been done, we create a Mapper between the UserObject class and UserAnotherObject class. This will be done using the following line.

AutoMapper.Mapper.CreateMap<UserObject, UserAnotherObject>();

After creating this Mapper, let’s put some data into the object of the class UserObject that we made above,

uObj.Id = 123;
uObj.Name = "Vipul";
uObj.Address = "Gurgaon";

Now that we have the data, let’s copy the data from the object of the UserObject class into the object of the class UserAnotherObject using the AutoMapper that we just created above.

uAnotherObj = AutoMapper.Mapper.Map<UserAnotherObject>(uObj);

This copies the complete data from the uObj object to the uAnotherObj object.

Note. We need to keep it in mind that Auto Mapper copies data to properties in the target object with the same name as the properties name in the source object. The name should be the same but NOT CASE-SENSITIVE i.e. the name in the source object can be “id” and that in the target object can be “ID”.

The values are copied into the target object as shown below.

Target object

Hope this article helped in understanding the basic usage of Auto Mapper in C#. Please find a working solution attached for better understanding.

Read more articles on C#.