AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. 

It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

Sometimes in real-time projects, the entity layers deal with the communication from services or DataLayers. To show the data in the application, we need to separate the class as ViewModel and Model class. However, UI Layers might fail to sync with the entities. Therefore, to map entities to model or viewModel, we need AutoMapper.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Why Do We Need to Use AutoMapper in C#?

Let’s understand why we need to use AutoMapper in C# through an example. 

Consider two classes, a source class (e.g., Student), and a destination class (e.g., StudentDT). We need to declare the classes with their data properties as shown in the image below.

   public class Student

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Department { get; set; }

    }   

    public class StudentDT

    {

        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 Student object to StudentDT object, we need to first create and populate the Student object. The below image shows how we can create and populate the Student object. 

Student stu = new Student();

stu.Name = "Shivam";

stu.Age = 20;

stu.Address = "Bihar";

stu.Department = "IT";

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

StudentDT stuDT = new StudentDT();

stuDT.Name = stu.Name;

stuDT.Age = stu.Age;

stuDT.Address = stu.Address;

stuDT.Department = stu.Department;

Actual Code Example Without Using C# AutoMapper

Now, let’s see the actual code example for mapping data from one object of the source class to another object of the destination class using the traditional approach, i.e., without using the C# AutoMapper.

namespace AutoMapperDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            Student stu = new Student();

            stu.Name = "Shivam";

            stu.Age = 20;

            stu.Address = "Bihar";

            stu.Department = "IT"; 

            StudentDT stuDT = new StudentDT();

            stuDT.Name = stu.Name;

            stuDT.Age = stu.Age;

            stuDT.Address = stu.Address;

            stuDT.Department = stu.Department;

            Console.WriteLine("Name:" + stuDT.Name + ", Age:" + stuDT.Age + ", Address:" + stuDT.Address + ", Department:" + stuDT.Department);

            Console.ReadLine();

        }

    }

    public class Student

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Department { get; set; }

    } 

    public class StudentDT

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Department { get; set; }

    }

}

Now, when we run our application, it gives us the output result as expected. But what if we need to increase the number of data properties? Well, we need to write all the code for new data properties and transform the data from the source class to the destination class, and as a result, we have to do the mapping again and again.

Even on real-time projects, sometimes we need to map objects between the UI/Domain and Services/Domain. However, it can become hectic to do the mapping using the traditional method as discussed earlier.

Hence, we use “AutoMapper” in C#.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

How Do I Use AutoMapper in C#?

To understand how to use AutoMapper in C#, let us look at an example using a console application.

In this example, we will create the same classes as before (Student, StudentDT) and map the data properties from the source class object to the destination class object using “AutoMapper” in C#. 

Here, Student is the source class, and StudentDT is the destination class.

We need to map each Student properties to the correspondent StudentDT properties using AutoMapper.

Procedure to use AutoMapper in C#

Step1: Installing the AutoMapper library

  • Open Package Manager Console window
  • Paste the command “Install-Package AutoMapper” library
  • Press enter to install the AutoMapper library.

Once installed, you can check your project references section to find AutoMapper.

After installing the AutoMapper, we can use it wherever we want and in may different ways. 

We will be using AutoMapper to map Student object with StudentDT object, to better understand the concept.

Step2: Initializing the AutoMapper

When our classes have been defined, we will create the MapperConfiguration object. There will be only one MapperCoinfiguration object per AppDomain and it should always be instantiated at application start-up.

Syntax:

var config = new MapperConfiguration(cfg =>

    cfg.CreateMap<TSource, TDestination>()

);

Now let’s see how to instantiate the AutoMapper with our example classes. 

var config = new MapperConfiguration(cfg =>

    cfg.CreateMap<Student,StudentDT>()

);

The below code shows how to initialize, and use AutoMapper in C#. 

//initializing the mapper

var config = new MapperConfiguration(cfg =>

    cfg.CreateMap<Student, StudentDT>()

);

//Using AutoMapper

var mapper = new Mapper(config);

var stuDT = mapper.Map<StudentDT>(stu);

//another way of initializing using AutoMapper

//var stuDT = mapper.Map<Student,StudentDT>(stu);

Code Implementation:

using System;

using AutoMapper;

namespace AutoMapperDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            //Initialize the mapper

            var config = new MapperConfiguration(cfg =>

                    cfg.CreateMap<Student, StudentDT>()

                ); 

            //Creating the source object

            Student stu = new Student

            {

                Name = "Shivam",

                Age = 20,

                Address = "Bihar",

                Department = "IT"

            }; 

            //Using AutoMapper

            var mapper = new Mapper(config);

            var stuDT = mapper.Map<StudentDT>(stu);

            //OR another way of initializing AutoMapper.

            //var stuDT2 = mapper.Map<Student, StudentDT>(stu);

//on running this , it will give us the output as expected

            Console.WriteLine("Name:" + stuDT.Name + ", Age:" + stuDT.Age + ", Address:" + stuDT.Address + ", Department:" + stuDT.Department);

            Console.ReadLine();

        }

    } 

    public class Student

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Department { get; set; }

    } 

    public class StudentDT

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Department { get; set; }

    }

}

When we run the application using AutoMapper, it will give us the output as expected.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

What Will Happen if Source and Destination Property Names Are Different?

To see what will happen if we change the property name of the objects, we will change the StudentDT class’s Name and Department property to Fullname and Dept in our example.

Let us see the code for this implementation:

using System;

using AutoMapper;

namespace AutoMapperDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            //Initialize the mapper

            var config = new MapperConfiguration(cfg =>

                    cfg.CreateMap<Student, StudentDT>()

                );

            //Creating the source object

            Student stu = new Student

            {

                Name = "Shivam",

                Age = 20,

                Address = "Bihar",

                Department = "IT"

            };

            //Using AutoMapper

            var mapper = new Mapper(config);

            var stuDT = mapper.Map<StudentDT>(stu);

            //OR another way of initializing AutoMapper.

            //var stuDT2 = mapper.Map<Student, StudentDT>(stu);

//on running this , it will give us the output as expected

            Console.WriteLine("Name:" + stuDT.Name + ", Age:" + stuDT.Age + ", Address:" + stuDT.Address + ", Department:" + stuDT.Department);

            Console.ReadLine();

        }

    }

    public class Student

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Department { get; set; }

    }

    public class StudentDT

    {

        //changing the name property for StudentDT from "Name" to "Fullname"

        public string Fullname { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        //changing the name of department property for StudentDT from "Department" to "Dept"

         public string Dept { get; set; }       

    }

}

If we run the above application after changing the property name of the destination class, the output field for both the properties, Name, and Department, will be empty.

Output:

//Name: , Age: 20, Address:Bihar, Department: 

So, if we change the property name, C# AutoMapper will not map those properties by default.

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

How to Map Two Properties When the Names Are Different Using AutoMapper?

As we know, if the data property name is different for source and destination classes, the AutoMapper in C# can’t map those properties by default. However, using the ForMember option, we can map between the properties of different names.

So, to map Name property with Full Name property, we need to map these properties in the mapping configuration as shown below.

var config = new MapperConfiguration(cfg =>

        cfg.CreateMap<Student, StudentDT>()

        .ForMember(dest => dest.Fullname, act => act.MapFrom(src => src.Name))

        .ForMember(dest => dest.Dept, act => act.MapFrom(src => src.Department))

);

Code Implementation:

Now let’s see the complete code implementation using ForMember :

using System;

using AutoMapper;

namespace AutoMapperDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            //Initialize the mapper

            var config = new MapperConfiguration(cfg =>

                    cfg.CreateMap<Student, StudentDT>()

                    .ForMember(dest => dest.Fullname, act => act.MapFrom(src => src.Name))

                    .ForMember(dest => dest.Dept, act => act.MapFrom(src => src.Department))

                );

            //Creating the source object

            Student stu = new Student

            {

                Name = "Shivam",

                Age = 20,

                Address = "Bihar",

                Department = "IT"

            }; 

            //Using AutoMapper

            var mapper = new Mapper(config);

            var stuDT = mapper.Map<StudentDT>(stu);

            //OR

            //var stuDT2 = mapper.Map<Student, StudentDT>(stu);

            Console.WriteLine("Name:" + stuDT.Fullname + ", Age:" + stuDT.Age + ", Address:" + stuDT.Address + ", Department:" + stuDT.Dept);

            Console.ReadLine();

        }

    } 

    public class Student

    {

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Department { get; set; }

    }

    public class StudentDT

    {

        public string Fullname { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }

        public string Dept { get; set; }

    }

}

This code will give us the output as expected.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion 

AutoMapper in C# is an open-source library present in GitHub where anybody can contribute.

It is crucial for mapping properties between objects. AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, 

Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well. One must be conversant with all the latest technologies being used in the tech industry and stay up to date with the technological trends. The Post Graduate Program in Full Stack Web Development course offered by Simplilearn will help you elevate your career as a software developer. You can also check out the SkillUp course platform,  a Simplilearn initiative to enhance your skills and advance your career.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors