liveBook · Manning

Data transfer object

As explained in .NET in Action, Second Edition

A data transfer object is an object that defines the data communicated across a boundary without necessarily exposing the structure of the underlying domain or persistence model.

A data transfer object (DTO) defines the data communicated across a boundary. It separates external communication from the domain or persistence model, allowing data to be flattened, circular references removed, and internal properties hidden. section 7.4.1

Use DTOs to make permitted operations explicit:

  • Represent creation and update as separate types, exposing only the fields each operation accepts. section 7.4.1
  • Pass DTOs through repository methods instead of exposing database entities directly. section 7.4.1
  • Prefer explicit types when direct entity use would depend on undocumented change tracking, ignored fields, or side effects. section 7.4.1
Listing 7.19 ICustomerRepository interface
namespace CustomerBatchImporter;
  
public interface ICustomerRepository
{
  Task CreateAsync(                                  #1
    NewCustomerDto customer);                        #2
  
  Task UpdateAsync(
    UpdateCustomerDto customer);
  
  Task<Customer?> GetByEmailAsync(string email);     #3
}
  
public record NewCustomerDto(                        #4
  string Email,
  string Name,
  string License
) { }                                                #5
  
public record UpdateCustomerDto(
  int Id,
  string? NewName,
  string? NewLicense
) { }

The repository interface demonstrates separate record DTOs for creating and updating customers. section 7.4.1

How .NET in Action, Second Edition covers it

How deep it goes
Defines DTO purpose and implements separate C# records for creation and update, without detailing serialization or validation.
Examples
Uses NewCustomerDto and UpdateCustomerDto in a customer repository called by a CSV importer.
What it assumes
Assumes familiarity with C# classes, interfaces, records, repositories, and database entities.
What you can do after
Build it from scratch by defining operation-specific records and passing them through explicit repository methods.
How it connects
Connects domain entities, database persistence, web API controllers, repositories, and EF Core change tracking.

Also explained in

Compare how 6 books explain data transfer object →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.