Skip to main content

Lesson 3 of 8

DTOs & AutoMapper

DTOs (Data Transfer Objects) separate your API contract from your domain model - you can change database schema without breaking API clients, and you never accidentally expose sensitive fields (passwords, internal IDs, audit timestamps). AutoMapper automates boilerplate mapping.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

DTO Layers & AutoMapper Profile

DTO Layers & AutoMapper Profile
using AutoMapper;

// ━━ Three DTO layers ━━

// 1. Request DTOs - what comes in (validated by FluentValidation/Data Annotations)
public record CreateProductRequest(
    string Name,
    decimal Price,
    string CurrencyCode,
    Guid CategoryId,
    int InitialStock,
    string? Description);

// 2. Response DTOs - what goes out (safe, client-friendly shape)
public record ProductResponse(
    Guid Id,
    string Name,
    string Slug,
    decimal Price,
    string CurrencyCode,
    string CategoryName,
    int StockQuantity,
    bool IsAvailable,    // computed: StockQuantity > 0
    DateTime CreatedAt);

// 3. Internal DTOs - between layers (projections, search results)
public record ProductSummary(Guid Id, string Name, decimal Price, bool IsAvailable);

// ━━ AutoMapper Profile - centralized mapping rules ━━
public class ProductMappingProfile : Profile
{
    public ProductMappingProfile()
    {
        // Entity → Response
        CreateMap<Product, ProductResponse>()
            .ForMember(d => d.CategoryName, opt => opt.MapFrom(s => s.Category.Name))
            .ForMember(d => d.IsAvailable,  opt => opt.MapFrom(s => s.StockQuantity > 0))
            .ForMember(d => d.CurrencyCode, opt => opt.MapFrom(s => "USD")); // hardcoded for now

        // Entity → Summary
        CreateMap<Product, ProductSummary>()
            .ForMember(d => d.IsAvailable, opt => opt.MapFrom(s => s.StockQuantity > 0));

        // Request → Entity (for creates)
        CreateMap<CreateProductRequest, Product>()
            .ForMember(d => d.Id,         opt => opt.MapFrom(_ => Guid.NewGuid()))
            .ForMember(d => d.Slug,       opt => opt.MapFrom(s => GenerateSlug(s.Name)))
            .ForMember(d => d.StockQuantity, opt => opt.MapFrom(s => s.InitialStock))
            .ForMember(d => d.IsDeleted,  opt => opt.Ignore())  // never map from request
            .ForMember(d => d.CreatedAt,  opt => opt.Ignore())  // set in DbContext.SaveChanges
            .ForMember(d => d.UpdatedAt,  opt => opt.Ignore());
    }

    private static string GenerateSlug(string name) =>
        name.ToLower().Replace(" ", "-").Replace("'", "").Trim();
}

// Registration:
builder.Services.AddAutoMapper(typeof(ProductMappingProfile).Assembly);

// Usage in service:
public class ProductService(IProductRepository repo, IMapper mapper)
{
    public async Task<ProductResponse?> GetByIdAsync(Guid id, CancellationToken ct)
    {
        var product = await repo.FindByIdAsync(id, ct);
        return product is null ? null : mapper.Map<ProductResponse>(product);
    }

    public async Task<ProductResponse> CreateAsync(CreateProductRequest request, CancellationToken ct)
    {
        var product = mapper.Map<Product>(request);
        repo.Add(product);
        await repo.SaveChanges_Placeholder(ct);
        return mapper.Map<ProductResponse>(product);
    }
}

// Placeholder
interface IMapper { TDest Map<TDest>(object src); }
class Product { public Guid Id { get; set; } public string Name { get; set; } = ""; public string Slug { get; set; } = ""; public decimal Price { get; set; } public int StockQuantity { get; set; } public bool IsDeleted { get; set; } public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } public Guid CategoryId { get; set; } public Category Category { get; set; } = null!; public string Description { get; set; } = ""; }
class Category { public Guid Id { get; set; } public string Name { get; set; } = ""; }
interface IProductRepository { Task<Product?> FindByIdAsync(Guid id, CancellationToken ct); void Add(Product p); Task SaveChanges_Placeholder(CancellationToken ct); }

Tip

Tip

Practice DTOs AutoMapper in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of DTOs AutoMapper from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with DTOs AutoMapper is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done