Mapping logic using Automapper

An alternative way is to implement the mapping using the Automapper NuGet package. As mentioned in Chapter 5, Web Service Stack in ASP.NET Core, this approach uses the reflection system provided by .NET in order to match and to map the fields of our classes. It is possible to add the Automapper package to the Catalog.Domain project using the following CLI instruction:

dotnet add package Automapper

Automapper uses a profile-based structure in order to define the mapping behaviors of our classes. Let's proceed by defining a new CatalogProfile class in the Mappers folder:

using AutoMapper;
using Catalog.Domain.Entities;
using Catalog.Domain.Requests.Item;
using Catalog.Domain.Responses.Item;

namespace Catalog.Domain.Mapper
{
public class CatalogProfile : Profile
{
public CatalogProfile()
{
CreateMap<ItemResponse, Item>().ReverseMap();
CreateMap<GenreResponse, Genre>().ReverseMap();
CreateMap<ArtistResponse, Artist>().ReverseMap();
CreateMap<Price, PriceResponse>().ReverseMap();
CreateMap<AddItemRequest, Item>().ReverseMap();
CreateMap<EditItemRequest, Item>().ReverseMap();
}
}
}

The preceding profile will be used by the dependency injection engine to define the lists of mapping behaviors. The CreateMap method provided by the Profile base class matches two generic types: TSource and TDestination. It will be possible to also perform the reverse process by chaining the ReverseMap() extension method. This can be applied for every request and response type we define in the application. In order to use the mapping logic in our methods, it is necessary to inject the IMapper type into the target class and execute the Map method in the following way:

_mapper.Map<ItemResponse>(new Item());

It is important to notice that the Map method will throw a runtime exception in the following cases:

  • The type of the source and the destination of the mapping don't correspond
  • The corresponding source and destination mapping is not explicitly defined in a profile
  • There are some unmapped members in the entities (this prevents accidental null fields in the destination of the mapping)

Finally, Automapper also requires initialization using the dependency injection of .NET Core. We will see how to add Automapper in the DI engine later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.2.122