C# / .NET Compendium PLEN
.NET / C# / AutoMapper

AutoMapper - object mapping

The problem it solves - manual mapping is tedious and error-prone

// Manual mapping - it works, but it grows and it's easy to make a mistake when you add a new field
public OrderDto MapToDto(Order order)
{
    return new OrderDto
    {
        Id = order.Id,
        CustomerName = order.Customer.Name, // nawigacja
        Total = order.TotalAmount,
        ItemCount = order.Items.Count
    };
}

For large objects with dozens of fields, manual mapping is a lot of repetitive code - and it's easy to forget to map a new field after adding it to the entity/DTO.

Basic Profile configuration

public class OrderMappingProfile : Profile
{
    public OrderMappingProfile()
    {
        CreateMap<Order, OrderDto>()
            .ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer.Name))
            .ForMember(dest => dest.ItemCount, opt => opt.MapFrom(src => src.Items.Count));
        // Total → TotalAmount is mapped AUTOMATICALLY if the names differ only by convention,
        // albo Id → Id, CustomerName → CustomerName gdy nazwy IDENTYCZNE - bez ForMember
    }
}

The automatic mapping convention: by default AutoMapper maps properties with identical names without any configuration - ForMember is needed only for fields requiring non-standard logic (a different name, a transformation, navigation through nested objects).

Registration in DI

builder.Services.AddAutoMapper(typeof(OrderMappingProfile).Assembly); // skanuje assembly, rejestruje WSZYSTKIE profile

Usage through IMapper (injected via DI - constructor injection, as always)

public class OrderService : IOrderService
{
    private readonly AppDbContext _context;
    private readonly IMapper _mapper;

    public OrderService(AppDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<OrderDto> GetOrderAsync(int id)
    {
        var order = await _context.Orders.Include(o => o.Customer).FirstOrDefaultAsync(o => o.Id == id);
        return _mapper.Map<OrderDto>(order); // one line instead of manual mapping
    }
}

ProjectTo<T>() - mapping AT THE SQL LEVEL (a key optimisation with EF Core)

This is the most important thing to know about AutoMapper in the context of EF Core - and it refers directly to the discussion of IQueryable/IEnumerable:

// ❌ INEFFICIENT - first materialises ALL the columns, THEN maps in memory
var orders = await _context.Orders.ToListAsync(); // SELECT * (wszystkie kolumny!)
var dtos = _mapper.Map<List<OrderDto>>(orders); // mapowanie w C#, po pobraniu WSZYSTKIEGO

// ✅ EFFICIENT - ProjectTo translates the mapping INTO a SQL SELECT with specific columns
var dtos = await _context.Orders
    .ProjectTo<OrderDto>(_mapper.ConfigurationProvider) // generuje SELECT TYLKO potrzebnych kolumn!
    .ToListAsync();

ProjectTo<T>() works on IQueryable (exactly the interface we discussed in detail) - AutoMapper analyses the mapping configuration and builds it into the query's expression tree, so EF Core generates a SQL SELECT with only the needed columns, instead of fetching the whole entity and mapping it in C# memory.

-- Map() po ToListAsync() - EF Core generuje:
SELECT * FROM Orders  -- WSZYSTKIE kolumny, w tym te niepotrzebne do OrderDto

-- ProjectTo() - EF Core generuje:
SELECT Id, TotalAmount, (SELECT COUNT(*) FROM OrderItems WHERE OrderId = Orders.Id) AS ItemCount
FROM Orders -- TYLKO kolumny potrzebne do OrderDto

Custom Value Resolvers - complex mapping logic

public class DiscountResolver : IValueResolver<Order, OrderDto, decimal>
{
    public decimal Resolve(Order source, OrderDto destination, decimal destMember, ResolutionContext context)
    {
        return source.TotalAmount * (source.Customer.IsVip ? 0.9m : 1.0m); // logic too complex for ForMember
    }
}

CreateMap<Order, OrderDto>()
    .ForMember(dest => dest.DiscountedTotal, opt => opt.MapFrom<DiscountResolver>());

Reverse mapping - ReverseMap()

CreateMap<Order, OrderDto>()
    .ReverseMap(); // automatically generates the OrderDto → Order mapping TOO

Configuration validation - AssertConfigurationIsValid()

// In tests - checks that ALL the mappings are complete (no field left unassigned without an exception)
var config = new MapperConfiguration(cfg => cfg.AddProfile<OrderMappingProfile>());
config.AssertConfigurationIsValid();

This is an important practice - by default AutoMapper does not throw an error if a destination field has no corresponding source (it keeps its default value) - AssertConfigurationIsValid() in a test catches such cases before deployment, instead of finding out about it from empty data in production.

The controversy around AutoMapper - worth knowing for the interview

This is a frequent topic of discussion (similar to Repository/UoW) - some teams avoid AutoMapper in favour of manual mapping methods or code generators (e.g. Mapperly - a newer alternative that generates code at compile time):

Arguments against AutoMapper: - "Magic" makes debugging harder - a mapping error shows up at runtime, not at compile time - Refactoring (renaming a field) is not safe - ForMember(dest => dest.OldName, ...) will still compile after the property is renamed, but will stop working correctly - Performance overhead for simple 1:1 mapping (although ProjectTo partly mitigates this)

Arguments for: - Less repetitive code with a large number of DTOs - ProjectTo gives a real, practical SQL optimisation without writing LINQ projections by hand

Summary

AutoMapper eliminates the repetitive code of manual mapping between entities and DTOs, through configuration in a Profile and a convention of matching by property names. The key, practical optimisation is ProjectTo<T>(), which - unlike Map() called after materialisation - works at the IQueryable level, translating the mapping into a SQL SELECT with only the needed columns, instead of fetching the whole entity and mapping it in C# memory.

Buy me a coffee