Tutorials Microservices with .NET
Payment Microservice — Complete Guide
Payment Microservice — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Microservices with .NET on Toolliyo Academy.
On this page
Microservices with .NET · Lesson 20 of 120
DTO and Mapping Strategies
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 2: Building Microservices
What is this?
DTOs (Data Transfer Objects) are simple classes for API JSON — CreateOrderDto, OrderSummaryDto. Mapping converts between DTOs and domain entities so database shape stays private.
Why should you care?
Exposing EF entities in JSON ties your API to database columns forever. DTOs let you rename tables without breaking mobile apps.
See it live — copy this example
Create a Web API project (dotnet new webapi), paste the code, then run dotnet run.
public record OrderLineDto(int ProductId, int Qty, decimal UnitPrice);
public record CreateOrderDto(Guid CustomerId, List<OrderLineDto> Lines);
public static class OrderMappings
{
public static Order ToEntity(CreateOrderDto dto) => new()
{
CustomerId = dto.CustomerId,
Lines = dto.Lines.Select(l => new OrderLine
{
ProductId = l.ProductId,
Qty = l.Qty,
UnitPrice = l.UnitPrice
}).ToList()
};
public static OrderSummaryDto ToSummary(Order o) => new(o.Id, o.Status, o.Total);
}
Run Example »
Edit the code and click Run — like W3Schools Try it Yourself.
What happened?
- CreateOrderDto comes from HTTP.
- ToEntity builds domain Order.
- ToSummary returns safe fields to client — no internal navigation properties.
Try it yourself
- Create DTOs in Order.Api/Dtos/ folder.
- Add OrderMappings static class.
- MapPost uses ToEntity before SaveChanges.
- Change a string or number in the example and run again — predict the output first.
- Break the code on purpose (remove a semicolon), read the compiler error, then fix it.
Remember
DTOs = API shape; entities = database/domain shape. Map in one place per direction. Do not leak EF entities over HTTP.
Real-world: Mobile app versioning
App v1 uses OrderSummaryDto with three fields. v2 adds EstimatedDelivery — new DTO or optional field without breaking v1.
Outcome: Backend evolves; old apps keep working until users upgrade.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!