In this article, I’ll discuss AutoMapper in C# with Examples. At the end of this article, you will be having a very good understanding of the followings:

What is AutoMapper?

AutoMapper is a C# library used for mapping data between objects in web development. It functions as an intermediary between two objects, converting one object type to another. The library facilitates the conversion of an input object of one type into an output object of another type, as long as the latter type adheres to the conventions of AutoMapper.

In certain real-world projects, the entity layers handle communication between services or data layers. To display data within the application, we must differentiate between the ViewModel and Model classes. However, there may be instances where the UI layers are unable to synchronize with the entities. In such cases, ‘AutoMapper’ is necessary for mapping entities to models or ‘ViewModels’.

Why do we need AutoMapper in C#?

Let’s contemplate on two categories, namely a starting category (e.g., Employee) and a target category (e.g., EmployeeDT). It is crucial to specify the categories along with their data characteristics as illustrated in the picture underneath.

public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }   
    public class EmployeeDT
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }

Now, to copy data from Employee object to EmployeeDT object, we need to first create and populate the Employee object. The below code shows how we can create and populate the Student object.

Employee emp = new Employee();
emp.Name = "Rakesh";
emp.Age =320;
emp.Address = "Delhi";
emp.Department = "IT";

After the Employee object is created, we need to create a EmployeeDT object and copy all the data from Employee object to EmployeeDT object as shown below.

EmployeeDT empDT = new EmployeeDT();
empDT.Name = emp.Name;
empDT.Age = emp.Age;
empDT.Address = emp.Address;
empDT.Department = emp.Department;

Above code is all done without Automapper.Now in below we’ll see this using Automapper.

static void Main(string[] args)
        {
            Employee e = new Employee ();
            emp.Name = "Smith";
            emp.Age = 25;
            emp.Address = "Delhi";
            emp.Department = "IT"; 
            EmployeeDT empDT = new EmployeeDT();
            empDT.Name = emp.Name;
            empDT.Age = emp.Age;
            empDT.Address = emp.Address;
            empDT.Department = emp.Department;
            Console.WriteLine("Name:" + empDT.Name);
            Console.WriteLine(" Age:" + empDT.Age);
            Console.WriteLine(" Address:" + empDT.Address );
            Console.WriteLine(Department:" + empDT.Department);
            Console.ReadLine();
        }
    }
    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    } 
    public class EmployeeDT
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}

Now, what if we need to increase the number of data properties? Then, we need to write all the code and map new data properties and transform the data from the source to destination class, and this required mapping again.  Hence, it will become hectic to do the mapping using the traditional method as discussed above. Here comes the role of automapper.

How to Use AutoMapper in C#?

Let’s understand it using one example below:

Installing AutoMapper Library in Your Project:

AutoMapper is a publicly available repository found on GitHub. To set up this repository, launch the Package Manager Console window. To access the Package Manager Console window, choose Tools => NuGet Package Manager => Package Manager Console from the dropdown menu as illustrated in the image below.

You can try using command Install-Package AutoMapper Package in Manager Console window

AutoMapper in C# with Examples

 You can also try using UI, right click on you project and (like mvc_sample in above screenshot) and choose the option as shown in below image.

AutoMapper in C# with Examples

If you face any issue in installing latest version, then you can give a try with older or stable version too. After installing the AutoMapper Library in your project, then it will add a reference of AutoMapper.DLL to your project and all it method will be easily accessible to you now.

AutoMapper in C# with Examples

AutoMapper Syntax:

Syntax:
var config = new MapperConfiguration(cfg =>

    cfg.CreateMap<TSource, TDestination>()

);

//initializing the mapper
var config = new MapperConfiguration(cfg =>
    cfg.CreateMap<Employee, EmployeeDT>()
);

How AutoMapper will work in example?

static void Main(string[] args)
        {
            //Initialize the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Student, StudentDT>()
                ); 
            //Creating the source object
            Employee emp = new employee
            {
                Name = "Smith",
                Age = 30,
                Address = "Delhi",
                Department = "IT"
            }; 
            //Using AutoMapper
            var mapper = new Mapper(config);
            var empDT = mapper.Map<EmployeeDT>(emp);
            //below is one another way of initializing AutoMapper.
            //var empDT2 = mapper.Map<Employee, EmployeeDT>(emp);
     //At runtime above code will give the output as expected
             empDT.Department = emp.Department;
            Console.WriteLine("Name:" + empDT.Name);
            Console.WriteLine(" Age:" + empDT.Age);
            Console.WriteLine(" Address:" + empDT.Address );
            Console.WriteLine(Department:" + empDT.Department);

            Console.ReadLine();
        }
    } 
    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    } 
    public class EmployeeDT
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}

In this post we discuss AutoMapper in C# with Examples, when we run the application using AutoMapper, it will map your model and give the desired output. You can check more such article on our C# Section.

I hope this post have given you insight on AutoMapper and you will be able to use this in you project. You can also visit HERE

Leave a Reply

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

Explore More

Working With File Class In C#

In C#, ‘File’ class provides many static methods for moving, copying, and deleting files. These Static methods involve moving a file and copying and deleting a file also. Let’s check

How to Read a Text File in C#

In C# ‘File’ class provides static methods to read given text file data. The File.ReadAllText() method opens a text file, reads all the text present in the file into a

C# | How to use Interface references

In C#, you’re permitted to make a reference variable of an interface type or in other words, you’re permitted to form an interface reference variable. Such kind of variable can