How Can AutoMapper Help You?

Justin Armstrong .NET, Technology Snapshot 2 Comments

There are many times that when developing when you need to map an object to another object. When these situations occur, AutoMapper is the answer. It can be used for a one-to-one mapping out-of-the-box or you can easily customize the mappings to meet your needs. This also helps with only having one place to make changes when objects change or grow and more mappings are needed.

This allows just having one place to translate the objects instead of possibly many places scattered throughout the code. There will only be one place that needs to be updated when or if the objects get updated in the future. AutoMapper can also be used to combine fields such as First and Last names from one object into a Full name field in the mapped object.

In this blog, I talk about how to get started with AutoMapper for one-to-one, dynamic mapping. I’ll show an example of using AutoMapper with a basic mapping and to create a custom mapping. Let’s get started.

How To Download AutoMapper

AutoMapper can be found at GitHub. To install AutoMapper, first install the NuGet Package Manager in Visual Studio IDE. Once the NuGet package manager is installed, open the NuGet console and enter the following command to install the AutoMapper library:

PM>  Install-Package AutoMapper

To verify the install check for a reference to the dll within your project in Visual Studio.

How To Map Objects Using AutoMapper

We can begin with a console application and create two classes Person and Student. For these uses the Person and Student classes will have most fields in common but Student will have one extra field. To show the output of the mapping we will overwrite the ToString() method. The code will look like this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
}
 
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; } //Extra Field
    public string Address { get; set; }
    public string PhoneNumber { get; set; }

	public override string ToString()
	{
		return String.Format(
            "First Name: {0} \r\nLast Name: {1} \r\nFull Name: {2} \r\nAddress: {3} \r\nPhone Number: {4}", 
            FirstName, LastName, FullName, Address, PhoneNumber);
	}
}

Now let’s start with the default mapping. To do this you just map the classes without adding any parameters. AutoMapper will automatically map properties with the same name. So in this example that would be the FirstName, LastName, Address, and PhoneNumber fields. This leaves the FullName field in Student not mapped as there is not an equivalent property in the Person class.

The syntax for a mapping is Mapper.CreateMap<T1, T2>() using the proper types. In this example T1 will be the Person class and T2 will be the Student class. Below is a snippet with only using the default mapping.

// Create the mapping of Person to Student
Mapper.CreateMap<Person, Student>();

// Create a person to use
var myPerson = new Person
{
FirstName = "Justin",
LastName = "Armstrong",
Address = "123 Any St",
PhoneNumber = "816-555-5555"
};

// Get the mapped Student from the Person object
Var myStudent = Mapper.Map<Person, Student>(myPerson);

Console.WriteLine(myStudent.ToString());

Output:

Now that we have seen what a default mapping looks like, let’s dive into adding in the custom mapping for the FullName field. We will need to use the ForMember() and MapFrom() extensions when creating the custom mapping.

This will not affect the default mapping functionality, meaning that we can leave the other fields alone and they will still map properly.

// Create the custom mapping of Person to Student
Mapper.CreateMap<Person, Student>()
	.ForMember(s => s.FullName,
 map => map.MapFrom(p => p.FirstName + “ “ + p.LastName));

// Create a person to use
var myPerson = new Person
{
FirstName = "Justin",
LastName = "Armstrong",
Address = "123 Any St",
PhoneNumber = "816-555-5555"
};

// Get the mapped Student from the Person object
Var myStudent = Mapper.Map<Person, Student>(myPerson);

Console.WriteLine(myStudent.ToString());

Output:

Now you can see that we have successfully mapped the FullName field in the custom mapping.

Summary

In this article you saw how to use AutoMapper with a basic mapping and to create a custom mapping.

Hopefully this has helped you get an understanding of AutoMapper and how you might be able to use it to help translate data in one place instead of needing to do it in multiple places over and over again.


About the Author
Justin Armstrong

Justin Armstrong

Justin Armstrong is a Kansas City-based Keyhole developer. He has been developing web applications for 10 years using C#, ASP.NET, and Java. His favorite hobby is playing ice hockey as a goalie. He also enjoys spending time and raising his two amazing kids with his wife, Charity.


Share this Post

Comments 2

    1. Justin Armstrong Post
      Author

Leave a Reply