Roadmap › ASP.NET Core Web API & REST › Module: Building Robust APIs
Lessons in this course (15)

7. DTOs, validation and mapping

Intermediate★ Must knowLesson 7 of 15
  • Never expose EF entities directly: use request/response DTOs (records) to avoid over-posting, circular references and leaking internal fields.
  • Validate with data annotations, FluentValidation, or .NET 10 Minimal API validation.
  • Map with hand-written mapping/extension methods, Mapperly (source generator) or AutoMapper (commercial licence since v15, 2025).
csharp
public record CreateOrderRequest([Required] int CustomerId, [MinLength(1)] List<OrderLineRequest> Lines);
public record OrderDto(int Id, string Customer, decimal Total, string Status);

public static class OrderMapping
{
    public static OrderDto ToDto(this Order o) => new(o.Id, o.Customer.Name, o.Total, o.Status.ToString());
}

public class CreateOrderValidator : AbstractValidator<CreateOrderRequest>
{
    public CreateOrderValidator() { RuleFor(x => x.CustomerId).GreaterThan(0); RuleForEach(x => x.Lines).ChildRules(l => l.RuleFor(x => x.Qty).InclusiveBetween(1, 100)); }
}