Smith5727
Smith5727

Reputation: 775

AutoMapper: Mapping between DTO and Entity

I am working with a ASP.NET Core WebAPI and I want to do CRUD for my objects called "Item". I am using EF Core to work with a SQL Database and I have two models that represents my objects.

  1. ItemDto - Data Transfer Object for an Item
  2. ItemEntity - Database Object (represents a row in a table 1:1)

My HTTP GET one and HTTP GET many methods works in such way that it

  1. Get ItemRepository instance

  2. Fetch one or more ItemEntity

  3. Map it to ItemDto by using AutoMapper This is initalized in my constructor such as

    m_itemDtoMapper = new Mapper(new MapperConfiguration(cfg => cfg.CreateMap<ItemEntity, ItemDto>()));
    

And in my WebAPI method I map it to a ItemDto with the following line (for the GET many case):

var itemDtos = m_itemDtoMapper.Map<IEnumerable<ItemEntity>, ICollection<ItemDto>>(items);

This works well and the AutoMapper is very powerful. The questions I have now is:

  1. Is this the standard way of managing the relationship between database entities and data transfer objects?
  2. In the CreateItem method, I need to do reverse mapping. Instead of mapping ItemEntity to ItemDto, I need to map a ItemDto to an ItemEntity. How shall I do this? Creating a copy of my mapper just with switched entities works but is that how its supposed to be done? i.e two mappers.

Upvotes: 1

Views: 7933

Answers (1)

vitalragaz
vitalragaz

Reputation: 328

In your example, it seems that you initialize each time a new mapper instance. I would suggest you go along with dependency injection and make use of AutoMapper Mapping Profiles.

You can do it in three simple steps and I think it answers both of your questions:

Step 1: Simply create a new class called MappingProfile or something similar:

   public class MappingProfile: Profile
    {
        public MappingProfile()
        {
            CreateMap<User, AuthenticateDto>(); // One Way
            CreateMap<User, UserDto>().ReverseMap(); // Reverse
        }
    }

Step 2: Register Automapper in Startup.cs

   // Register AutoMapper
   services.AddAutoMapper(Assembly.GetExecutingAssembly());

Step 3: Consume your mapper over DI

  public UserService(IMapper mapper) {
   _mapper = mapper;
  }
// call it as you already did
_mapper.Map<User, UserDto>(user);

Hopefully it helps you :)

Upvotes: 6

Related Questions