What is AutoMapper?

AutoMapper is a C# library which allows to do the mapping automatically between two similar objects. Typically really useful to map for example a domain model to a DTO (Data Transfer Object) or from a UI model to other layers of your code.

Why should you use AutoMapper?

Of course you always can do the mapping manually. But the issue with that, is the fact that objects can evolve (add new properties for example), and in that case you will need to remember every time your object changes that you need to update the mapping code.

How to use AutoMapper?

Basically, all you need are two very similar objects and some mapping conventions. These mapping conventions can be configured in different ways but I personally thing that the easiest way is to use a MappingProfile.

First you will need to install the NuGet package AutoMapper.

Let’s start by creating our simple domain model:

public class PersonModel { public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public override string ToString() { return $"{FirstName} {LastName}"; } }
Code language: C# (cs)

Now we will create the DTO:

public class PersonDTO { public string FirstName { get; set; } public string LastName { get; set; } }
Code language: C# (cs)

Let’s create the MappingProfile:

public class MappingProfile : Profile { public MappingProfile() { CreateMap<PersonModel, PersonDTO>().ReverseMap(); } }
Code language: C# (cs)

Observe the inheritance from Profile (from AutoMapper) and the ReverseMap which allows us to map in both directions automatically.

Let’s write some simple .Net 6 code to test our mapping:

using AutoMapper; using AutoMapper.Configuration; using AutoMapperDemo; IMapper Mapper; var cfg = new MapperConfigurationExpression(); cfg.AddProfile<MappingProfile>(); var mapperConfig = new MapperConfiguration(cfg); Mapper = new Mapper(mapperConfig); var person = new PersonModel { FirstName = "Elon", LastName = "Musk" }; Console.WriteLine(person); PersonDTO mappedPerson = Mapper.Map<PersonDTO>(person); Console.WriteLine(mappedPerson); Console.WriteLine(mappedPerson.FirstName);
Code language: C# (cs)

This code will simply configure AutoMapper to use our MappingProfile, then we will create a new Person object (which contains a method ToString to be able to display our object with its FirstName and LastName).

By doing the mapping of our PersonModel to the PersonDTO, we lost the ToString method, because indeed a DTO should not contain any method.

So when we display on screen the PersonModel, we can see that the ToString is displaying the FirstName and the LastName. Doing the same on the mapped object will only display the type of the object. But if we display the FirstName of that mapped object, we can see that the mapping actually worked!

Happy coding! 🙂