ASP.NET Core AutoMapper

By | 2019-06-20

Mappers solve the problem of copying/translating data from one model to another. I’ve been using AutoMapper for some years and it does the job without too much hassle, and supports a lot of complex scenarios.

I mainly use it for easy mapping of fields of same name between classes, but also for validation. If you rename a variable and forget to update other places the compiler will tell you, but in the case of mapping it may go unnoticed. Having AutoMapper validate the mapping and ensuring you have to add ignore to missing mappings can be useful to avoid bugs.

Install

This will automatically install AutoMapper dependency.

Implement

In Startup.cs ConfigureServices:

The parameter typeof(startup) describes what assembly to scan for Profiles.

Use

First we have to define a Profile for mapping between classes. This is done by having a class inherit from Profile, which will be picked up by AutoMapper automagically. Note that there are many options for complex model mapping, check AutoMapper documentation for more.

Then we need to get IMapper in a controller:

For this test mapper we need a couple of classes:

And to use it:

Validation

In Startup.cs add “IMapper mapper” as parameter to Configure() and run vaildation.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IMapper mapper)
{
mapper.ConfigurationProvider.AssertConfigurationIsValid();
...
}

Leave a Reply

Your email address will not be published. Required fields are marked *