Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 3 · Lesson 23 · 6 min read

DTOs vs Entities in ASP.NET Core APIs

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: An Entity, Its DTOs and a Projection
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Separate persistence entities from API contracts using purpose-built request and response types, explain how returning entities causes data exposure and tight coupling, and choose a mapping approach that keeps queries efficient and mistakes visible at compile time.

Concept Explanation

An entity is a class shaped for storage: it mirrors a table, includes foreign keys and navigation properties, and often contains fields the outside world should never see, such as password hashes, internal notes, soft delete flags, or tenant identifiers. A data transfer object, or DTO, is a class shaped for a conversation with a client: it contains exactly the fields one operation needs. Returning an entity directly from an endpoint is the shortest path to a demo and the most common cause of both accidental data leaks and painful breaking changes, because the database schema and the public contract become the same thing.

The exposure risk is the OWASP API Security category Broken Object Property Level Authorization, which covers exposing too many properties in responses and accepting too many in requests. When the entity gains a new column, such as an internal risk score or an email verification token, it appears in every response that returns that entity, immediately and silently. Attributes like JsonIgnore on the entity reduce the problem but invert the safe default: everything is exposed unless someone remembers to hide it. DTOs invert it correctly: nothing is exposed unless someone deliberately adds it, and a code review of the DTO shows exactly what leaves the system.

Coupling is the second cost. If the React application depends on the shape of your table, then renaming a column, splitting a table, or normalizing data forces a breaking API change. With DTOs the database can evolve freely behind a stable contract, and different clients or versions can have different DTOs over the same entities. Also, entities frequently contain cycles, for example an order referencing its customer, who references orders, and serializers either fail or produce enormous payloads when they follow navigation properties into the graph.

For mapping, prefer explicit code. Simple static mapping methods, or source generators such as Mapperly, are compile-time checked, easy to debug, and fast. Reflection-based mappers like AutoMapper, which moved to a commercial license model in 2025, hide behavior behind convention and can throw at runtime for a missing mapping. For read endpoints, the best mapping is often a projection inside the query itself: a LINQ Select into the DTO makes Entity Framework select only those columns, so sensitive fields are never even loaded from the database. That combines the security benefit and the performance benefit in one line.

AspectReturning entitiesUsing DTOs
Exposed fieldsEverything, including future columnsOnly what the DTO declares
Schema changesBreak the API contractAbsorbed behind the mapping
SerializationMay follow cycles or load huge graphsFlat, predictable shape
Request bindingEnables mass assignmentAllowlist of writable fields
Query efficiencyLoads all columnsProjection selects only needed columns
Code reviewMust inspect the whole entityContract is visible in one small type

Worked Example: An Entity, Its DTOs and a Projection

The entity carries sensitive and internal fields. The DTOs define the contract for reading and writing. The endpoint projects directly in the query, and a small extension shows explicit mapping where projection is not possible.

C#
// Persistence shape: never leaves the server.
public class UserEntity
{
    public Guid Id { get; set; }
    public string Email { get; set; } = "";
    public string DisplayName { get; set; } = "";
    public string PasswordHash { get; set; } = "";       // must never be serialized
    public bool IsAdmin { get; set; }
    public int RiskScore { get; set; }                   // internal signal
    public string? InternalNotes { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
}

// Contract shapes: each field is a deliberate decision.
public record UserSummaryDto(Guid Id, string DisplayName);                       // shown to other users
public record UserProfileDto(Guid Id, string DisplayName, string Email);         // shown to the owner only
public record UpdateProfileRequest([property: Required, StringLength(80)] string DisplayName);

// Projection: EF selects just Id and DisplayName; the hash and notes are never read.
app.MapGet("/api/users", async (AppDb db, CancellationToken ct) =>
    TypedResults.Ok(await db.Users
        .OrderBy(u => u.DisplayName)
        .Select(u => new UserSummaryDto(u.Id, u.DisplayName))
        .ToListAsync(ct)));

// Explicit mapping when the entity is already loaded.
public static class UserMapping
{
    public static UserProfileDto ToProfile(this UserEntity u) => new(u.Id, u.DisplayName, u.Email);
}

app.MapGet("/api/me", async (AppDb db, ClaimsPrincipal caller, CancellationToken ct) =>
{
    var id = caller.GetUserId();                          // from the verified identity
    var user = await db.Users.FindAsync([id], ct);
    return user is null ? Results.NotFound() : Results.Ok(user.ToProfile());
}).RequireAuthorization();

Adding a column to UserEntity changes nothing the client sees. To expose it, someone must edit a DTO and a mapping, and a reviewer sees the change. Notice also that the summary DTO used for other users omits email, while the profile DTO used for the owner includes it: the same entity can have several contracts for different audiences.

A user entity contains a password hash, admin flag and internal notes. A projection selects only the columns each audience may see into DTOs, while returning the entity directly would expose every current and future column.
A user entity contains a password hash, admin flag and internal notes. A projection selects only the columns each audience may see into DTOs, while returning the entity directly would expose every current and future column.

Real-World Examples

  • In January 2021, researchers reported that Peloton's API returned private profile details such as age, gender, city, and workout statistics for users who had set their accounts to private, and to callers who were not authenticated at all. The data existed in the backend objects and the API simply serialized more than the interface needed, an exposure that response types limited to displayed fields would have prevented.
  • The OWASP API Security Top 10 2023 lists Broken Object Property Level Authorization as API3, merging the earlier categories of excessive data exposure and mass assignment. Its prevention guidance says to avoid generic binding and serialization helpers, return only the properties needed, and use explicit response schemas, which is exactly what per-operation DTOs provide.
Key TakeawaysEntities describe how data is stored and DTOs describe what the API says, and keeping the two separate makes exposing a field a deliberate act. It also decouples the contract from the schema and allows different shapes for different audiences. Map explicitly or by source generation, and project inside the query so unneeded and sensitive columns are never even loaded.

Review Questions & Answers

Every property, including ones added later, is serialized automatically, so sensitive or internal fields such as password hashes, flags, and notes can reach clients without anyone deciding they should. The default is exposure unless each field is hidden. A response DTO reverses that default, so a field is sent only when it has been deliberately added to the contract.

Entity Framework translates the Select into SQL that reads only the columns the DTO needs, so sensitive columns are never fetched from the database into memory, and less data moves across the connection. The result is a smaller attack surface, less memory use, and faster queries in one change.

Different audiences are entitled to different information. Other users may see a display name, while the owner may also see their email. Separate types make each audience's contract explicit and reviewable, and avoid the pattern of one large object with fields conditionally blanked, which is easy to get wrong.

Explicit and generated mappings are checked at compile time, so a missing or misnamed property is a build error rather than a production exception, and the code can be read and debugged directly. Convention-based reflection mappers can hide behavior, surprise you with silent mismatches, and impose runtime cost, and licensing terms for some have changed, so a simple approach reduces risk.