- ASP.NET Core MVC
- ASP.NET Core logging with Serilog
- ASP.NET Core managed config
- ASP.NET Core MVC with /api/-area
- ASP.NET Core API versioning
- ASP.NET Core API with Swagger UI
- ASP.NET Core EF in separate project
- ASP.NET Core AutoMapper
- ASP.NET Core response cache
- ASP.NET Core memory cache
- ASP.NET Core TypeScript

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
1 |
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection |
This will automatically install AutoMapper dependency.
Implement
In Startup.cs ConfigureServices:
1 |
services.AddAutoMapper(typeof(Startup)); |
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.
1 2 3 4 5 6 7 |
public class TestProfile : Profile { public TestProfile() { CreateMap<SourceClass, DestinationClass>(); } } |
Then we need to get IMapper in a controller:
1 2 3 4 5 6 7 8 9 10 |
public class TestController : ControllerBase { private readonly IMapper _mapper; public TestController(IMapper mapper) { _mapper = mapper; } ... } |
For this test mapper we need a couple of classes:
1 2 3 4 5 6 7 8 9 |
public class SourceClass { public string Name { get; set; } } public class DestinationClass { public string Name { get; set; } } |
And to use it:
1 2 3 |
var s = new SourceClass() {Name = "Test1"}; var d = _mapper.Map<DestinationClass>(s); // s.Name == d.Name |
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();
...
}