Skip to content

Automapper

Yann edited this page Aug 14, 2018 · 3 revisions

What is automapper

Automapper is a package which can help you creating your mappings between your entities. As an example, instead of doing your mapping from your DTO to your Domain object manually, you could let Automapper make this mapping by convention and just set the configuration instead of all the explicit mappings.

Get Automapper

To use automapper in your project, just install it from the NuGet repository : https://www.nuget.org/packages/AutoMapper/

Configure Automapper for .NET core 2

Once the package is referenced from NuGet, you'll have to specify which models are mapped together. Open you project Startup.cs file and search for the method with the following signature : public void Configure(IApplicationBuilder app, IHostingEnvironment env). In that method, add the automapper configuration like

AutoMapper.Mapper.Initialize(cfg =>
{
    cfg.CreateMap<User, UserDto>().ReverseMap();
    cfg.CreateMap<UserForCreationDto, User>();
});

The basic configuration is often enough as Automapper maps by convention (http://docs.automapper.org/en/stable/Conventions.html). Sometimes you'll want to be able not to map only in one direction (source to target) but also the other way around. In that case, just add the .ReverseMap() as you can see in the example above.

If you need custom mappings like to map to another property or to map multiple properties to one, you can use Custom Value Resolvers

Use Automapper

Then in your code, just map with : var mappedObject = Mapper.Map<MyTargetModel>(mySourceObject);

Clone this wiki locally