SHARE:

Common features in ASP.NET Core 2.2 WebApi: Mapping

 

Introduction

The data mapping is a very likely need to transform objects into other objects (similar or not) as the application layers interact with each other (dto -> domain objects and vice versa).
There are different ways to proceed. It is possible to create services, create classic static classes or extension methods.

In this article we will talk about AutoMapper.

AutoMapper is convention-based object-object mapper.

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values. AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.

Installation

Download this package:

PM> Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

This package will install everything you need, AutoMapper itself and necessary dll to use AutoMapper with Injection Dependency in ASP.NET Core.

Configuring Startup.cs 

Pretty simple at this step.

We just need to add AutoMapper at the ServiceCollection like this:

public void ConfigureServices(IServiceCollection services)
{
   // Automapper
   services.AddAutoMapper();
}

Then we just need to write AutoMapper profiles and thees profiles will be loaded when the application starts. No need to register them in the Startup.cs.

Create profiles

Profiles are a collection of mapping strategy. Each strategy is defined with method CreateMap<TSource,TDestination>.

In the next sample we will use two objects that are differents and that need a precise mapping strategy (UserEntity to map in a User dto):

public class UserEntity
{
   public string Id { get; set; }
   public Gender Gender { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
public class User
{
   public string Gender { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string SIN { get; set; }
}

As we can see, their signature is not the same, Id needs to be mapped to SIN, and Gender needs to be casted to a string.

Let’s see how we can achieve this:

public class MyMappingProfiles : Profile
{
   public MyMappingProfiles()
   {
      CreateMap<UserEntity, User>()
      .ForMember(dest => dest.Gender, source => source.MapFrom(src => src.Gender.ToString()))
      .ForMember(dest => dest.FirstName, source => source.MapFrom(src => src.FirstName.ToUpper()))
      .ForMember(dest => dest.LastName, source => source.MapFrom(src => src.LastName.ToUpper()))
      .ForMember(dest => dest.SIN, source => source.MapFrom(src => src.Id));
   }
}

The important thing here is to inherit from Profile class. When the application starts, every classes that inherit from a Profile class will be registered by AutoMapper and the mapping strategy will be enabled.

How to use a mapping strategy ? Let’s go to the next section!

Using a mapping strategy

Let’s create a Controller and inject in the constructor the interface IMapper as follow:

[Route("api/[controller]")]
[ApiController]
public class DemoMappingController : ControllerBase
{
   private IMapper _mapper;

   public DemoMappingController(IMapper mapper)
   {
      _mapper = mapper;
   }

   [HttpGet("getuser")]
   public ActionResult<User> Get()
   { 
      var entity = new UserEntity
      {
         Gender = Gender.Mister,
         FirstName = "Anthony",
         LastName = "Giretti",
         Id = "123456789"
      };

   return Ok(_mapper.Map<User>(entity));
}

Because the Nuget package we installed (AutoMapper +  Injection Dependency extensions for AutoMapper) we are able to use AutoMapper by calling the interface IMapper.

In order to execute the mapping let’s call the map method like this: _mapper.Map<TDestination>(objectToMap)

Demo!

Conclusion

With Automapper you can map one object to another throughout your application with just a little configuration.

This example was really simple. AutoMapper can really handle more complex mappings.

I leave you the opportunity to deepen the subject hoping that this article convinced you to use AutoMapper 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: