AutoMapper is a popular object-to-object mapping library that can be used to map objects belonging to dissimilar types. As an example, you might need to map the DTOs (Data Transfer Objects) in your application to the model objects. AutoMapper saves you the tedious effort of having to manually map one or more properties of such incompatible types.

To start working with AutoMapper, you should create a project in Visual Studio and then install AutoMapper. You can install AutoMapper from NuGet using the following command in the NuGet Package Manager Console window:

PM> Install-Package AutoMapper

Create mappings using AutoMapper

An object-to-object mapper such as AutoMapper converts an input object of one type into an output object of another type. Consider the following two classes.

An AutoMapper example

Let’s now work with some data. Refer to the following piece of code that stores some data into the source object and then displays the property values in the destination object after the mapping is done.

When you execute the above piece of code, the author name stored inside the destination object will be displayed. However, the values of the destination FirstName and destination LastName properties will be the same as the source object because you have mapped the objects successfully using AutoMapper!

Note that AutoMapper can map any set of classes. However, AutoMapper follows certain conventions, one of which is that the property names being mapped should have identical names. If the property names are not identical, then you must let AutoMapper know how the properties should be mapped. Assuming that we want to map the two properties Contact and ContactDetails, the following example illustrates how this can be achieved.

Note the following statement that is used to create the destination object.

var destination = iMapper.Map<AuthorModel, AuthorDTO>(source);

If the destination object already exists, you can use the statement below instead.

iMapper.Map(sourceObject, destinationObject);

In essence, the above code snippet can be used to map two objects that already exist.

Using projections in AutoMapper

AutoMapper provides excellent support for projections. Projections are used to map source values to a destination that does not match the structure of the source. (By contrast, the mapping we discussed above was a one-to-one mapping.)

Let’s now look at a projection. For example, consider the following class.

Joydip Kanjilal is a Microsoft MVP in ASP.Net, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .Net and related technologies.