Dev guide :: .NET Backend

.NET Backend

Build GameCatalog, a REST API for video games and their developers, with .NET 10, ASP.NET Core Minimal APIs, EF Core, and PostgreSQL 18. Docker runs the SDK, database, and integration tests. On Windows, you need Docker Desktop in Linux container mode and a text editor.

The first milestone is a request that reaches PostgreSQL and returns a JSON response. Later chapters add database guarantees, reproducible HTTP tests, interactive documentation, and a paginated list. Examples show the relevant files or excerpts at each step.

C# is the language. The .NET SDK builds and tests the code. The .NET runtime executes it. ASP.NET Core handles HTTP routing, binding, dependency injection, and middleware. EF Core translates supported LINQ queries and coordinates database writes through the Npgsql provider.

flowchart LR
    CSharp[C#] --> DotNet[.NET Runtime + BCL + tooling]
    DotNet --> AspNet[ASP.NET Core]
    DotNet --> Console[Console / Worker]
    DotNet --> EF[Entity Framework Core]

Docker development environment

Create a GameCatalog directory and put the Dockerfile and Compose file below at its root. The SDK image includes build tools and runs as a development container. The Compose service binds the source directory into the container and publishes the API on the Windows loopback interface.

dockerfile
FROM mcr.microsoft.com/dotnet/sdk:10.0

WORKDIR /workspace
RUN dotnet tool install --global dotnet-ef --version 10.0.0
ENV PATH="${PATH}:/root/.dotnet/tools"

EXPOSE 8080
CMD ["dotnet", "run", "--no-launch-profile", "--project", "src/GameCatalog.Api", "--urls", "http://0.0.0.0:8080"]
yaml
services:
  api:
    build: .
    ports:
      - "127.0.0.1:8080:8080"
    volumes:
      - .:/workspace
      - api-obj:/workspace/src/GameCatalog.Api/obj
      - api-bin:/workspace/src/GameCatalog.Api/bin
      - tests-obj:/workspace/src/GameCatalog.Tests/obj
      - tests-bin:/workspace/src/GameCatalog.Tests/bin
    environment:
      ASPNETCORE_ENVIRONMENT: Development
      DOTNET_USE_POLLING_FILE_WATCHER: "1"
      ConnectionStrings__GameCatalog: Host=db;Port=5432;Database=gamecatalog;Username=postgres;Password=postgres
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:18
    environment:
      POSTGRES_DB: gamecatalog
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    volumes:
      - postgres-data:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d gamecatalog"]
      interval: 5s
      timeout: 5s
      retries: 5

volumes:
  postgres-data:
  api-obj:
  api-bin:
  tests-obj:
  tests-bin:

The API connects to db:5432 over the Compose network. Windows connects to the published API port at localhost:8080. PostgreSQL 18 stores its versioned data directory under the named volume mounted at /var/lib/postgresql. The separate bin and obj volumes keep Linux build outputs away from the Windows source tree.

flowchart LR
    Editor["Windows editor"] -->|writes files| Sources["Project directory"]
    Sources -->|bind mount| Api[".NET SDK container"]
    Client["Windows HTTP client"] -->|localhost:8080| Api
    Api -->|db:5432| Db[("PostgreSQL 18")]
    Db -->|stores data| Volume[("Named Docker volume")]

Run the following commands from PowerShell at the project root. The template is an initial scaffold. Replace its startup code with the wiring shown later as you add the data model, endpoints, and error handler.

powershell
docker compose build api
docker compose run --rm --no-deps api dotnet new sln -n GameCatalog
docker compose run --rm --no-deps api dotnet new web -n GameCatalog.Api -o src/GameCatalog.Api --framework net10.0
docker compose run --rm --no-deps api dotnet sln GameCatalog.slnx add src/GameCatalog.Api/GameCatalog.Api.csproj

The environment variable ConnectionStrings__GameCatalog maps to the configuration key ConnectionStrings:GameCatalog. The example credentials are for the local tutorial. The polling file watcher can help when changes arrive through a bind mount. Use dotnet run if watch fails with a static web assets error and restart it after source edits.

Entities and relationships

A developer can have zero or more games. Every game has one developer. DeveloperId is the foreign key stored in the Games table. Developer and Games are navigation properties used by EF Core. The null-forgiving initializer on Developer only affects compiler analysis. EF Core populates the navigation when the query or relationship fix-up supplies it.

erDiagram
    DEVELOPER ||--o{ GAME : develops

    DEVELOPER {
        int Id PK
        string Name
    }

    GAME {
        int Id PK
        string Name
        int ReleaseYear
        int DeveloperId FK
    }
csharp
namespace GameCatalog.Api.Models;

public class Developer
{
    public int Id { get; set; }
    public required string Name { get; set; }

    public ICollection<Game> Games { get; set; } = [];
}
csharp
namespace GameCatalog.Api.Models;

public class Game
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public int ReleaseYear { get; set; }

    public int DeveloperId { get; set; }
    public Developer Developer { get; set; } = null!;
}

Add the EF Core design package for migration tooling and the Npgsql provider for PostgreSQL. This example pins the tutorial to the 10.0 package family. Keep the provider, EF Core, and migration tool on compatible versions when upgrading.

xml
<ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
        <PrivateAssets>all</PrivateAssets>
        <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
</ItemGroup>

GameDbContext exposes the two entity sets. The Fluent API makes the unique names and foreign key explicit. HasIndex returns an index builder, so start again at Entity to configure the relationship. The name of a database constraint or unique index becomes part of the error mapping later in the guide.

csharp
using GameCatalog.Api.Models;
using Microsoft.EntityFrameworkCore;

namespace GameCatalog.Api.Data;

public class GameDbContext(DbContextOptions<GameDbContext> options) : DbContext(options)
{
    public DbSet<Game> Games => Set<Game>();
    public DbSet<Developer> Developers => Set<Developer>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Game>()
            .HasIndex(game => game.Name)
            .IsUnique();

        modelBuilder.Entity<Developer>()
            .HasIndex(developer => developer.Name)
            .IsUnique();

        modelBuilder.Entity<Game>()
            .HasOne(game => game.Developer)
            .WithMany(developer => developer.Games)
            .HasForeignKey(game => game.DeveloperId)
            .HasConstraintName("FK_Games_Developers_DeveloperId");
    }
}

Migrations and schema recovery

EF Core compares the current model against its checked-in model snapshot to generate a migration. Inspect Up and Down before applying it. Moving configuration from conventions to Fluent API may leave the relational model identical. Use the pending-model check to see whether there is a difference.

powershell
docker compose run --rm api dotnet ef migrations add InitialCreate --project src/GameCatalog.Api
docker compose run --rm api dotnet ef database update --project src/GameCatalog.Api
docker compose run --rm api dotnet ef migrations list --project src/GameCatalog.Api
docker compose run --rm api dotnet ef migrations has-pending-model-changes --project src/GameCatalog.Api

Start with InitialCreate for the model shown here. If you built the model in stages, a separate AddUniqueNames migration can add the indexes. Check existing data for duplicates before applying that change. A generated migration updates source files and the snapshot. Database update applies migration operations to PostgreSQL and records them in __EFMigrationsHistory.

flowchart LR
    M["Entities and Fluent API"] --> A["Generate migration"]
    S["Previous model snapshot"] --> A
    A --> F["Migration files and updated snapshot"]
    F --> U["Apply pending migrations"]
    U --> D[("PostgreSQL schema and migration history")]

PostgreSQL error 42P01 means the named relation could not be found. After deleting the development volume, verify the connection string and rerun database update to create the schema in the new database. Compose down stops the stack. Compose down -v also deletes its named volumes and the stored catalog data.

HTTP contracts and validation

Separate input records from EF entities. A caller sends a developer ID when writing a game. The game response includes the developer name for display. A DTO makes that contract explicit and avoids serializing EF navigation cycles or accepting client changes to database-owned fields such as Id.

csharp
using System.ComponentModel.DataAnnotations;

public record CreateDeveloperRequest(
    [Required, StringLength(100, MinimumLength = 2)] string Name);
public record DeveloperResponse(int Id, string Name);

public record CreateGameRequest(
    [Required, StringLength(100, MinimumLength = 2)] string Name,
    [Range(1, int.MaxValue)] int DeveloperId,
    [Range(1950, 2100)] int ReleaseYear);
public record UpdateGameRequest(
    [Required, StringLength(100, MinimumLength = 2)] string Name,
    [Range(1, int.MaxValue)] int DeveloperId,
    [Range(1950, 2100)] int ReleaseYear);
public record GameResponse(int Id, string Name, string Developer, int ReleaseYear);

DataAnnotations express input rules such as name length, positive IDs, and a release-year range. AddValidation enables validation for supported endpoint parameters in ASP.NET Core 10. The application service checks whether the requested developer exists. PostgreSQL enforces the foreign key even if the developer is deleted between the check and the insert.

flowchart LR
    Input["HTTP input"] --> Transport["Input rules: name length and ID range"]
    Transport --> UseCase["Application rule: developer exists"]
    UseCase --> Db["Database: foreign key and unique indexes"]

Startup and dependency injection

Program.cs is the composition root. It reads configuration, registers services and middleware, and maps routes. Keep HTTP binding and status codes in endpoint modules, use cases in services, and EF configuration in GameDbContext. AddDbContext registers a scoped context by default. Each request gets its own scope, which disposes the context when the request ends.

csharp
using Microsoft.EntityFrameworkCore;
using Scalar.AspNetCore;
using GameCatalog.Api.Data;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<GameDbContext>((services, options) =>
{
    var configuration = services.GetRequiredService<IConfiguration>();
    var connectionString = configuration.GetConnectionString("GameCatalog")
        ?? throw new InvalidOperationException("GameCatalog connection string is missing.");
    options.UseNpgsql(connectionString);
});
builder.Services.AddScoped<IGameService, GameService>();
builder.Services.AddScoped<IDeveloperService, DeveloperService>();
builder.Services.AddValidation();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddOpenApi();

var app = builder.Build();
app.UseExceptionHandler();
app.MapGameEndpoints();
app.MapDeveloperEndpoints();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}

app.Run();

Assemble GameService with the read, write, and paginated methods below. The interface lists the operations the endpoints use. Keep the earlier unpaged example as a comparison when adding pagination.

csharp
public interface IGameService
{
    Task<GameResponse?> GetByIdAsync(int id, CancellationToken ct);
    Task<GameResponse> CreateAsync(CreateGameRequest request, CancellationToken ct);
    Task<bool> UpdateAsync(int id, UpdateGameRequest request, CancellationToken ct);
    Task<PagedResponse<GameResponse>> GetAllAsync(GameQuery query, CancellationToken ct);
}

// Place the game read and write methods in this class.
public sealed class GameService(GameDbContext db, ILogger<GameService> logger) : IGameService
{
    // GetByIdAsync, CreateAsync, UpdateAsync, and the paginated GetAllAsync.
}
flowchart LR
    R1[HTTP Request] --> S1[DI Scope]
    S1 --> GS[GameService]
    S1 --> DB[GameDbContext]
    DB --> PG[(PostgreSQL)]

Keep the service registration and endpoint parameter type aligned. Registering GameService and asking for IGameService leaves the interface unresolved. Minimal APIs may then infer a request body, and a GET endpoint can fail during startup. Register the interface and implementation together, or request the concrete service at both sites.

A DbContext is a unit of work for a request and does not support concurrent operations. Await each query before starting another on the same instance. Pass the request CancellationToken down to EF Core so it can observe cancellation.

Reading data with EF Core

Build an IQueryable by composing filters, ordering, and projection. EF Core translates the expression when a terminal operation such as ToListAsync, FirstOrDefaultAsync, AnyAsync, or CountAsync executes it. Materializing early changes later filters into in-memory operations and can pull unnecessary rows across the network.

flowchart LR
    LINQ[LINQ expression] --> Tree[Expression Tree]
    Tree --> EF[EF Core provider]
    EF --> SQL[SQL]
    SQL --> PG[(PostgreSQL)]

Project directly to a response DTO. EF Core can translate Developer.Name into the required join without Include. Use Include when you need to materialize related entities. AsNoTracking communicates read intent and avoids tracking when entities are materialized. This scalar DTO projection already returns no entity instances to track.

csharp
public Task<GameResponse?> GetByIdAsync(int id, CancellationToken ct)
{
    return db.Games
        .AsNoTracking()
        .Where(g => g.Id == id)
        .Select(g => new GameResponse(
            g.Id,
            g.Name,
            g.Developer.Name,
            g.ReleaseYear))
        .FirstOrDefaultAsync(ct);
}

The method can return FirstOrDefaultAsync directly because its task type matches the signature. ToListAsync returns Task of List, which cannot be returned directly as Task of IEnumerable. Await the list before returning it as an enumerable. Await inside a try block when that block needs to catch asynchronous failures.

csharp
public async Task<IEnumerable<GameResponse>> GetAllAsync(CancellationToken ct)
{
    return await db.Games
        .AsNoTracking()
        .OrderBy(g => g.Name)
        .Select(g => new GameResponse(
            g.Id,
            g.Name,
            g.Developer.Name,
            g.ReleaseYear))
        .ToListAsync(ct);
}

Writing data and tracking changes

To create a game, resolve its developer, add the new entity, and save. EF sets the foreign key from the navigation and populates the generated game ID after the insert. A structured log preserves the ID as a searchable property.

csharp
public async Task<GameResponse> CreateAsync(CreateGameRequest request, CancellationToken ct)
{
    var developer = await db.Developers.FindAsync([request.DeveloperId], ct);

    if (developer is null)
        throw new DeveloperNotFoundException(request.DeveloperId);

    var game = new Game
    {
        Name = request.Name,
        Developer = developer,
        ReleaseYear = request.ReleaseYear
    };

    db.Games.Add(game);

    await db.SaveChangesAsync(ct);

    logger.LogInformation("Game {GameId} created", game.Id);

    return new GameResponse(
        game.Id,
        game.Name,
        developer.Name,
        game.ReleaseYear);
}

For an update, load a tracked game, validate the replacement developer, then change the name, year, and relationship. SaveChangesAsync detects modifications. Return a not-found result when the game ID does not exist. Remove marks a tracked entity for deletion.

csharp
public async Task<bool> UpdateAsync(int id, UpdateGameRequest request, CancellationToken ct)
{
    var game = await db.Games.FindAsync([id], ct);
    if (game is null)
        return false;

    var developer = await db.Developers.FindAsync([request.DeveloperId], ct)
        ?? throw new DeveloperNotFoundException(request.DeveloperId);

    game.Name = request.Name;
    game.ReleaseYear = request.ReleaseYear;
    game.Developer = developer;

    await db.SaveChangesAsync(ct);
    return true;
}
stateDiagram-v2
    [*] --> Unchanged: Load tracked entity
    Unchanged --> Modified: Change detected
    Modified --> Unchanged: UPDATE on save
    [*] --> Added: Add
    Added --> Unchanged: INSERT on save
    Unchanged --> Deleted: Remove
    Deleted --> [*]: DELETE on save

Unit of work and transactions

Let the use case decide when to save. A single SaveChangesAsync can insert a developer and its first game atomically. EF Core orders the inserts and propagates the generated key. Calling SaveChanges separately inside each repository could commit the developer before the game insert fails.

csharp
public async Task<DeveloperResponse> CreateWithGameAsync(CreateDeveloperWithGameRequest request, CancellationToken ct)
{
    var developer = new Developer { Name = request.DeveloperName };

    var game = new Game
    {
        Name = request.GameName,
        ReleaseYear = request.ReleaseYear,
        Developer = developer
    };

    db.Developers.Add(developer);
    db.Games.Add(game);

    await db.SaveChangesAsync(ct);

    return new DeveloperResponse(developer.Id, developer.Name);
}

For a use case that must span several saves, begin an explicit database transaction and commit after every required operation succeeds. Disposal rolls back a transaction that never commits. An HTTP call or message publish belongs to a separate system and cannot be rolled back by PostgreSQL.

csharp
await using var transaction = await db.Database.BeginTransactionAsync(ct);

// Apply the first set of changes.
await db.SaveChangesAsync(ct);
// Apply the second set of changes.
await db.SaveChangesAsync(ct);

await transaction.CommitAsync(ct);

DbSet already supports entity queries and changes, while DbContext coordinates the save. A repository that only forwards generic calls adds little to this tutorial. Consider one when it can express a meaningful domain operation or isolate a real persistence boundary.

Concurrent writes and database constraints

An existence query can improve the error message but two requests can both see the name as available. The unique index decides which insert can commit. A similar race occurs if a developer disappears after the service has checked the ID. PostgreSQL enforces both invariants for every database client.

sequenceDiagram
    participant A as Request A
    participant B as Request B
    participant DB as PostgreSQL
    A->>DB: Check game name
    DB-->>A: No match
    B->>DB: Check game name
    DB-->>B: No match
    A->>DB: Insert and commit
    DB-->>A: Success
    B->>DB: Insert the same name
    DB-->>B: 23505 unique violation
sequenceDiagram
    participant A as Create game
    participant B as Delete developer
    participant DB as PostgreSQL
    A->>DB: Read developer 42
    DB-->>A: Found
    B->>DB: Delete developer 42 and commit
    A->>DB: Insert game with DeveloperId 42
    DB-->>A: 23503 foreign key violation

PostgreSQL uses SQLSTATE 23505 for a unique violation and 23503 for a foreign-key violation. Match both SQLSTATE and the expected index or constraint name. Human-readable detail can change and may contain database values. Keep unknown violations on the unexpected-error path.

csharp
using Microsoft.EntityFrameworkCore;
using Npgsql;

public static class DatabaseExceptionTranslator
{
    public static bool TryTranslate(DbUpdateException exception, out Exception? translated)
    {
        translated = exception.InnerException switch
        {
            PostgresException
                { SqlState: PostgresErrorCodes.UniqueViolation, ConstraintName: "IX_Games_Name" }
                => new GameAlreadyExistsException(exception),
            PostgresException
                { SqlState: PostgresErrorCodes.UniqueViolation, ConstraintName: "IX_Developers_Name" }
                => new DeveloperAlreadyExistsException(exception),
            PostgresException
                { SqlState: PostgresErrorCodes.ForeignKeyViolation, ConstraintName: "FK_Games_Developers_DeveloperId" }
                => new InvalidDeveloperReferenceException(exception),
            _ => null
        };
        return translated is not null;
    }
}

public sealed class GameAlreadyExistsException(Exception cause)
    : Exception("Game already exists", cause) { }

public sealed class DeveloperAlreadyExistsException(Exception cause)
    : Exception("Developer already exists", cause) { }

public sealed class InvalidDeveloperReferenceException(Exception cause)
    : Exception("Invalid developer reference", cause) { }

public sealed class DeveloperNotFoundException(int id)
    : Exception($"Developer {id} does not exist") { }

The override below covers the asynchronous save overload used by the tutorial. If the application starts using other save overloads, give them the same policy or centralize translation at the use-case boundary. A bare throw preserves the original stack for errors the translator does not recognize.

csharp
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
    try
    {
        return await base.SaveChangesAsync(cancellationToken);
    }
    catch (DbUpdateException exception)
    {
        if (DatabaseExceptionTranslator.TryTranslate(exception, out var translated))
            throw translated!;

        throw;
    }
}

Problem Details and HTTP status codes

An exception handler maps known application failures to stable HTTP responses. The tutorial uses 409 for duplicate names, 400 for an invalid developer reference, 404 when the requested game itself is absent, and 500 for an unexpected server failure. Validation failures can include an errors object keyed by field. Keep SQL, connection strings, and stack traces in server diagnostics.

csharp
using Microsoft.AspNetCore.Diagnostics;

public sealed class GlobalExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext context, Exception exception, CancellationToken cancellationToken)
    {
        var problem = exception switch
        {
            GameAlreadyExistsException => (409, "Game already exists"),
            DeveloperAlreadyExistsException => (409, "Developer already exists"),
            DeveloperNotFoundException or InvalidDeveloperReferenceException
                => (400, "Invalid developer reference"),
            _ => ((int, string)?)null
        };

        if (problem is not { } mapped)
            return false;

        await Results.Problem(statusCode: mapped.Item1, title: mapped.Item2).ExecuteAsync(context);
        return true;
    }
}
flowchart TD
    Service[GameService] --> Save[SaveChangesAsync]
    Save --> PG[(PostgreSQL)]
    PG -->|23505| DBEx[DbUpdateException]
    DBEx --> Translator[DatabaseExceptionTranslator]
    Translator --> DomainEx[GameAlreadyExistsException]
    DomainEx --> Handler[GlobalExceptionHandler]
    Handler --> HTTP[HTTP 409 ProblemDetails]
http
HTTP/1.1 409 Conflict
Content-Type: application/problem+json

{
  "title": "Game already exists",
  "status": 409
}

Typed endpoints and API documentation

Group endpoints by resource and give the item lookup a stable route name. TypedResults exposes the handler’s direct outcomes in its return type. Document middleware outcomes separately with ProducesProblem and validation with ProducesValidationProblem. A successful POST uses the lookup route to generate a Location header.

csharp
using Microsoft.AspNetCore.Http.HttpResults;

public static class GameEndpoints
{
    public static void MapGameEndpoints(this IEndpointRouteBuilder endpoints)
    {
        var group = endpoints.MapGroup("/games").WithTags("Games");
        group.MapGet("/{id:int}", GetById).WithName("GetGameById");
        group.MapPut("/{id:int}", Update)
            .ProducesValidationProblem();
        group.MapPost("/", Create)
            .ProducesProblem(StatusCodes.Status400BadRequest)
            .ProducesValidationProblem()
            .ProducesProblem(StatusCodes.Status409Conflict);
    }

    private static async Task<Results<Ok<GameResponse>, NotFound>> GetById(
        int id, IGameService service, CancellationToken ct)
    {
        var game = await service.GetByIdAsync(id, ct);
        return game is null ? TypedResults.NotFound() : TypedResults.Ok(game);
    }

    private static async Task<Results<NoContent, NotFound>> Update(
        int id, UpdateGameRequest request, IGameService service, CancellationToken ct)
    {
        return await service.UpdateAsync(id, request, ct)
            ? TypedResults.NoContent()
            : TypedResults.NotFound();
    }

    private static async Task<CreatedAtRoute<GameResponse>> Create(
        CreateGameRequest request, IGameService service, CancellationToken ct)
    {
        var game = await service.CreateAsync(request, ct);
        return TypedResults.CreatedAtRoute(game, "GetGameById", new { id = game.Id });
    }
}

The developer service supplies the parent resource used by game creation. Register its routes separately under /developers.

csharp
using Microsoft.EntityFrameworkCore;
using GameCatalog.Api.Data;
using GameCatalog.Api.Models;

public interface IDeveloperService
{
    Task<DeveloperResponse> CreateAsync(CreateDeveloperRequest request, CancellationToken ct);
    Task<DeveloperResponse?> GetByIdAsync(int id, CancellationToken ct);
}

public sealed class DeveloperService(GameDbContext db) : IDeveloperService
{
    public async Task<DeveloperResponse> CreateAsync(CreateDeveloperRequest request, CancellationToken ct)
    {
        var developer = new Developer { Name = request.Name };
        db.Developers.Add(developer);
        await db.SaveChangesAsync(ct);
        return new DeveloperResponse(developer.Id, developer.Name);
    }

    public Task<DeveloperResponse?> GetByIdAsync(int id, CancellationToken ct) =>
        db.Developers.Where(developer => developer.Id == id)
            .Select(developer => new DeveloperResponse(developer.Id, developer.Name))
            .FirstOrDefaultAsync(ct);
}

public static class DeveloperEndpoints
{
    public static void MapDeveloperEndpoints(this IEndpointRouteBuilder endpoints)
    {
        var group = endpoints.MapGroup("/developers").WithTags("Developers");
        group.MapGet("/{id:int}", async Task<IResult> (
            int id, IDeveloperService service, CancellationToken ct) =>
        {
            var developer = await service.GetByIdAsync(id, ct);
            return developer is null ? Results.NotFound() : Results.Ok(developer);
        }).WithName("GetDeveloperById");
        group.MapPost("/", async (
            CreateDeveloperRequest request, IDeveloperService service, CancellationToken ct) =>
        {
            var developer = await service.CreateAsync(request, ct);
            return TypedResults.CreatedAtRoute(developer, "GetDeveloperById", new { id = developer.Id });
        }).ProducesValidationProblem().ProducesProblem(StatusCodes.Status409Conflict);
    }
}

The development environment exposes the OpenAPI document at /openapi/v1.json and Scalar at /scalar/v1. OpenAPI describes the contract. Scalar reads the document and provides an interactive client. Add the corresponding packages to the API project and keep both development endpoints inside the environment check in Program.cs.

powershell
docker compose run --rm --no-deps api dotnet add src/GameCatalog.Api package Microsoft.AspNetCore.OpenApi --version 10.0.0
docker compose run --rm --no-deps api dotnet add src/GameCatalog.Api package Scalar.AspNetCore
flowchart LR
    API["Minimal API + TypedResults"] --> OA["OpenAPI /openapi/v1.json"]
    OA --> SC["Scalar /scalar/v1"]
    SC --> API

Use the developer ID returned by the first request when creating the game. Then follow the game’s Location header. Repeat the game POST to see the conflict response and try a missing developer ID to exercise the foreign-key validation path.

http
POST /developers HTTP/1.1
Host: localhost:8080
Content-Type: application/json

{"name":"Larian Studios"}

POST /games HTTP/1.1
Host: localhost:8080
Content-Type: application/json

{"name":"Baldur's Gate 3","developerId":1,"releaseYear":2023}

HTTP/1.1 201 Created
Location: /games/1
Content-Type: application/json

{"id":1,"name":"Baldur's Gate 3","developer":"Larian Studios","releaseYear":2023}

GET /games/1 HTTP/1.1
Host: localhost:8080

Filtering, sorting, and pagination

GET /games accepts a developer filter, a minimum year, a sort field, a direction, and page settings. Defaults are name ascending, page one, and twenty items per page. Keep transport values nullable to distinguish omitted input. Convert them to a typed application query after binding and validation.

http
GET /games?page=2&pageSize=20
GET /games?developer=Ubisoft&minYear=2015
GET /games?sortBy=releaseYear&descending=true

The handler can explicitly validate the bound query object with DataAnnotations and return ValidationProblem for invalid values. This makes the behavior of the aggregated AsParameters object explicit. Binding failures such as a nonnumeric page can still be rejected by the framework before the handler runs.

csharp
using System.ComponentModel.DataAnnotations;

public enum GameSortField { Name, ReleaseYear }

public record GameQuery(
    string? Developer, int? MinYear, GameSortField SortBy,
    bool Descending, int Page, int PageSize);

public class GameQueryParameters
{
    public string? Developer { get; init; }
    [Range(1950, 2100)]
    public int? MinYear { get; init; }
    [RegularExpression("^(name|releaseYear)$")]
    public string? SortBy { get; init; }
    public bool? Descending { get; init; }
    [Range(1, 1_000_000)]
    public int? Page { get; init; }
    [Range(1, 100)]
    public int? PageSize { get; init; }

    public GameQuery ToQuery() => new(
        Developer, MinYear,
        SortBy == "releaseYear" ? GameSortField.ReleaseYear : GameSortField.Name,
        Descending ?? false, Page ?? 1, PageSize ?? 20);
}
csharp
// Import System.ComponentModel.DataAnnotations and Microsoft.AspNetCore.Http.HttpResults.
// In MapGameEndpoints:
group.MapGet("/", GetAll).WithName("GetGames").ProducesValidationProblem();

// In GameEndpoints:
private static async Task<Results<Ok<PagedResponse<GameResponse>>, ValidationProblem>> GetAll(
    [AsParameters] GameQueryParameters parameters, IGameService service, CancellationToken ct)
{
    var results = new List<ValidationResult>();
    if (!Validator.TryValidateObject(
        parameters, new ValidationContext(parameters), results, validateAllProperties: true))
    {
        var errors = results
            .SelectMany(result => result.MemberNames.DefaultIfEmpty(string.Empty),
                (result, member) => (member, message: result.ErrorMessage ?? "Invalid value"))
            .GroupBy(error => error.member)
            .ToDictionary(group => group.Key, group => group.Select(error => error.message).ToArray());
        return TypedResults.ValidationProblem(errors);
    }

    return TypedResults.Ok(await service.GetAllAsync(parameters.ToQuery(), ct));
}
json
{
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "Page": ["The field Page must be between 1 and 1000000."]
  }
}

Build the filtered query once. Count its matches before applying Skip and Take, then fetch the requested page. Use a unique tie breaker such as Id when rows share a release year. The page limit below also keeps the maximum offset within the range of an integer for all supported page sizes.

flowchart TD
    Params["Bound query parameters"] --> Query["Validated application query"]
    Query --> Filter["Filter IQueryable"]
    Filter --> Count["COUNT of filtered rows"]
    Filter --> Sort["Order by requested field, then Id"]
    Sort --> Page["OFFSET and LIMIT"]
    Page --> Project["Project to GameResponse"]
    Count --> Output["PagedResponse"]
    Project --> Output
csharp
public record PagedResponse<T>(
    IReadOnlyList<T> Items,
    int Page,
    int PageSize,
    int TotalCount);
csharp
public async Task<PagedResponse<GameResponse>> GetAllAsync(GameQuery query, CancellationToken ct)
{
    var games = db.Games.AsNoTracking();

    if (!string.IsNullOrWhiteSpace(query.Developer))
        games = games.Where(game => game.Developer.Name == query.Developer);
    if (query.MinYear is int minYear)
        games = games.Where(game => game.ReleaseYear >= minYear);

    var total = await games.CountAsync(ct);
    var sorted = (query.SortBy, query.Descending) switch
    {
        (GameSortField.ReleaseYear, true) => games.OrderByDescending(game => game.ReleaseYear),
        (GameSortField.ReleaseYear, false) => games.OrderBy(game => game.ReleaseYear),
        (_, true) => games.OrderByDescending(game => game.Name),
        _ => games.OrderBy(game => game.Name)
    };

    var items = await sorted
        .ThenBy(game => game.Id)
        .Skip((query.Page - 1) * query.PageSize)
        .Take(query.PageSize)
        .Select(game => new GameResponse(
            game.Id, game.Name, game.Developer.Name, game.ReleaseYear))
        .ToListAsync(ct);

    return new PagedResponse<GameResponse>(items, query.Page, query.PageSize, total);
}
json
{
  "items": [
    {
      "id": 12,
      "name": "Rayman Legends",
      "developer": "Ubisoft",
      "releaseYear": 2013
    }
  ],
  "page": 1,
  "pageSize": 20,
  "totalCount": 1
}

The count and the page are separate SQL statements, so concurrent writes can affect them differently. Offset pagination also gets more expensive as offsets grow and can shift rows between visits. If that becomes a problem, consider keyset pagination with a cursor over the same fully ordered columns.

Integration tests with real PostgreSQL

Use an xUnit test project that references the API. WebApplicationFactory runs the ASP.NET Core application with an in-process test server and supplies an HttpClient. Testcontainers starts a real PostgreSQL instance on a random published port. This combination exercises routing, binding, DI, SQL generation, migrations, PostgreSQL constraints, and error serialization.

powershell
docker compose run --rm --no-deps api dotnet new xunit -n GameCatalog.Tests -o src/GameCatalog.Tests --framework net10.0
docker compose run --rm --no-deps api dotnet sln GameCatalog.slnx add src/GameCatalog.Tests/GameCatalog.Tests.csproj
docker compose run --rm --no-deps api dotnet add src/GameCatalog.Tests/GameCatalog.Tests.csproj reference src/GameCatalog.Api/GameCatalog.Api.csproj
docker compose run --rm --no-deps api dotnet add src/GameCatalog.Tests package Microsoft.AspNetCore.Mvc.Testing --version 10.0.0
docker compose run --rm --no-deps api dotnet add src/GameCatalog.Tests package Testcontainers.PostgreSql
docker compose run --rm --no-deps api dotnet add src/GameCatalog.Tests package Respawn
flowchart LR
    Test["xUnit test"] --> Client["Factory HttpClient"]
    Client --> Api["In-process ASP.NET Core"]
    Api --> EF["EF Core with Npgsql"]
    EF --> Pg[("Disposable PostgreSQL")]
    Pg --> Api
    Api --> Assert["Assert HTTP status, headers, and JSON"]

In this Docker Desktop workflow, the test runner is itself a container. Mount the Docker socket only for the test command so the runner can ask the host Docker engine to start sibling containers. Inside the runner, 127.0.0.1 refers to the runner. The PostgreSQL test port is reached via host.docker.internal on Docker Desktop.

flowchart LR
    Runner["Test runner container"] -->|Docker socket| Engine["Host Docker engine"]
    Engine -->|starts| Db["PostgreSQL test container"]
    Runner -->|host.docker.internal and mapped port| Host["Docker Desktop port forwarding"]
    Host --> Db
powershell
docker compose run --rm --no-deps -v /var/run/docker.sock:/var/run/docker.sock -e TESTCONTAINERS_HOST_OVERRIDE=host.docker.internal api dotnet test GameCatalog.slnx

Ryuk is the Testcontainers resource reaper. If its initialization times out, first check Docker socket access and the published port path. The source tutorial temporarily used TESTCONTAINERS_RYUK_DISABLED=true in its local lab. Disposing containers still cleans up on a normal exit, but a crashed process can leave resources behind with Ryuk disabled.

Test fixtures and database reset

Start the PostgreSQL container, then pass its connection string into the factory as configuration before the host builds. That lets the test use the same AddDbContext registration as the application. Apply migrations through a scoped context obtained from the factory so the test exercises the schema used by the real app.

csharp
// Program.cs in the API project, after app.Run():
public partial class Program { }

// GameCatalogApiFactory.cs in the test project:
public sealed class GameCatalogApiFactory(string connectionString)
    : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration((_, configuration) =>
        {
            configuration.AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["ConnectionStrings:GameCatalog"] = connectionString
            });
        });
    }
}

Reuse a container across tests when startup is expensive. After migrating once, initialize Respawn with the PostgreSQL adapter and exclude __EFMigrationsHistory. Reset application rows before each test. Tests that share the same database must run serially, or one reset can delete another test’s data. Dispose the factory and container when the fixture ends.

flowchart TD
    Fixture[IntegrationTestFixture]
    Fixture --> PG[Start PostgreSQL once]
    Fixture --> M[Migrate once]
    Fixture --> R[Initialize Respawn once]
    Fixture --> API[Create ASP.NET app once]
    R --> Reset[Reset DB before each test]
csharp
// xUnit v2 fixture. Import EF Core, Npgsql, Respawn, Respawn.Graph,
// Testcontainers.PostgreSql, and the ASP.NET Core DI extensions.
public sealed class IntegrationTestFixture : IAsyncLifetime
{
    private readonly PostgreSqlContainer postgres = new PostgreSqlBuilder("postgres:18")
        .WithDatabase("gamecatalog_test")
        .WithUsername("postgres")
        .WithPassword("postgres")
        .Build();
    private Respawner respawner = null!;

    public GameCatalogApiFactory Factory { get; private set; } = null!;

    public async Task InitializeAsync()
    {
        await postgres.StartAsync();
        Factory = new GameCatalogApiFactory(postgres.GetConnectionString());

        await using var scope = Factory.Services.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
        await db.Database.MigrateAsync();

        await using var connection = new NpgsqlConnection(postgres.GetConnectionString());
        await connection.OpenAsync();
        respawner = await Respawner.CreateAsync(connection, new RespawnerOptions
        {
            DbAdapter = DbAdapter.Postgres,
            TablesToIgnore = [new Table("__EFMigrationsHistory")]
        });
    }

    public async Task ResetAsync()
    {
        await using var connection = new NpgsqlConnection(postgres.GetConnectionString());
        await connection.OpenAsync();
        await respawner.ResetAsync(connection);
    }

    public async Task DisposeAsync()
    {
        try
        {
            if (Factory is not null)
                await Factory.DisposeAsync();
        }
        finally
        {
            await postgres.DisposeAsync();
        }
    }
}

Worked integration tests

Test the happy path by creating a developer, creating a game with the returned ID, and following Location. Send a second developer POST with the same name to check the unique index and the complete 409 mapping. Also test a game with an unknown developer ID and assert the documented 400 outcome.

The class below shows how to reset the fixture before each test and dispose the client afterwards. Keep these examples in the same test class so xUnit runs them sequentially against that fixture.

csharp
public sealed class GameApiTests(IntegrationTestFixture fixture)
    : IClassFixture<IntegrationTestFixture>, IAsyncLifetime
{
    private HttpClient Client = null!;

    public async Task InitializeAsync()
    {
        await fixture.ResetAsync();
        Client = fixture.Factory.CreateClient();
    }

    public Task DisposeAsync()
    {
        Client?.Dispose();
        return Task.CompletedTask;
    }

    // Put the test methods below here.
}
csharp
[Fact]
public async Task CreateDuplicateDeveloper_ReturnsConflict()
{
    var request = new CreateDeveloperRequest("CD Projekt Red");
    var firstResponse = await Client.PostAsJsonAsync("/developers", request);
    Assert.Equal(HttpStatusCode.Created, firstResponse.StatusCode);

    var secondResponse = await Client.PostAsJsonAsync("/developers", request);
    Assert.Equal(HttpStatusCode.Conflict, secondResponse.StatusCode);

    var problem = await secondResponse.Content.ReadFromJsonAsync<ProblemDetails>();
    Assert.NotNull(problem);
    Assert.Equal(StatusCodes.Status409Conflict, problem.Status);
    Assert.Equal("Developer already exists", problem.Title);
}
csharp
[Fact]
public async Task CreateGame_WithExistingDeveloper_ReturnsCreated()
{
    var developerResponse = await Client.PostAsJsonAsync("/developers", new CreateDeveloperRequest("Larian Studios"));
    Assert.Equal(HttpStatusCode.Created, developerResponse.StatusCode);

    var developer = await developerResponse.Content.ReadFromJsonAsync<DeveloperResponse>();
    Assert.NotNull(developer);

    var gameResponse = await Client.PostAsJsonAsync("/games", new CreateGameRequest(
        "Baldur's Gate 3",
        developer.Id,
        2023));

    Assert.Equal(HttpStatusCode.Created, gameResponse.StatusCode);

    var game = await gameResponse.Content.ReadFromJsonAsync<GameResponse>();

    Assert.NotNull(game);
    Assert.Equal("Baldur's Gate 3", game.Name);
    Assert.Equal("Larian Studios", game.Developer);
    Assert.Equal(2023, game.ReleaseYear);
    Assert.True(game.Id > 0);

    var location = gameResponse.Headers.Location;
    Assert.NotNull(location);
    var fetched = await Client.GetFromJsonAsync<GameResponse>(location);
    Assert.Equal(game, fetched);
}
csharp
[Fact]
public async Task CreateGame_WithUnknownDeveloper_ReturnsBadRequest()
{
    var response = await Client.PostAsJsonAsync("/games",
        new CreateGameRequest(
            "Unknown Game",
            999999,
            2026));

    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

    var problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
    Assert.NotNull(problem);
    Assert.Equal(StatusCodes.Status400BadRequest, problem.Status);
}

For list tests, seed known data through a scoped GameDbContext, then act through the HTTP endpoint. A regression in the write endpoint will not break read-test setup. Assert exact item order, page metadata, and the count before pagination. Cover a filter, descending year sorting with a tie, and invalid page input.

csharp
public async Task SeedGamesAsync()
{
    using var scope = fixture.Factory.Services.CreateScope();

    var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();

    var ubisoft = new Developer { Name = "Ubisoft" };
    var valve = new Developer { Name = "Valve" };
    var idSoftware = new Developer { Name = "id Software" };

    db.Games.AddRange(
        new Game { Name = "Rayman Legends", ReleaseYear = 2013, Developer = ubisoft },
        new Game { Name = "Far Cry 5", ReleaseYear = 2018, Developer = ubisoft },
        new Game { Name = "Half-Life", ReleaseYear = 1998, Developer = valve },
        new Game { Name = "Portal 2", ReleaseYear = 2011, Developer = valve },
        new Game { Name = "Doom", ReleaseYear = 1993, Developer = idSoftware }
    );

    await db.SaveChangesAsync();
}
csharp
[Fact]
public async Task GetGames_ReturnsPagedResult()
{
    await SeedGamesAsync();

    var response = await Client.GetAsync("/games?page=2&pageSize=2");
    response.EnsureSuccessStatusCode();

    var result = await response.Content.ReadFromJsonAsync<PagedResponse<GameResponse>>();

    Assert.NotNull(result);
    Assert.Equal(2, result.Page);
    Assert.Equal(2, result.PageSize);
    Assert.Equal(5, result.TotalCount);
    Assert.Equal(2, result.Items.Count);

    Assert.Equal(["Half-Life", "Portal 2"], result.Items.Select(g => g.Name));
}
csharp
[Fact]
public async Task GetGames_WithInvalidPage_ReturnsBadRequest()
{
    var response = await Client.GetAsync("/games?page=0");
    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

    var problem = await response.Content.ReadFromJsonAsync<HttpValidationProblemDetails>();
    Assert.NotNull(problem);
    Assert.Contains("Page", problem.Errors.Keys);
}

Project layout and design choices

Start with separate folders for endpoints, DTOs, services, models, and data. It keeps the common pieces easy to find while the project is small. Move toward feature folders when working on one use case repeatedly sends you across many directories. A vertical slice can group the route, input, and handler for one operation while sharing the database context.

plaintext
GameCatalog/
├── GameCatalog.slnx
├── compose.yaml
├── Dockerfile
│
└── src/
    ├── GameCatalog.Api/
    │   ├── Program.cs
    │   │
    │   ├── Data/
    │   │   ├── GameDbContext.cs
    │   │   └── DatabaseExceptionTranslator.cs
    │   │
    │   ├── Models/
    │   │   ├── Game.cs
    │   │   └── Developer.cs
    │   │
    │   ├── Dtos/
    │   │   └── ...
    │   │
    │   ├── Endpoints/
    │   │   ├── GameEndpoints.cs
    │   │   └── DeveloperEndpoints.cs
    │   │
    │   ├── Services/
    │   │   ├── IGameService.cs
    │   │   ├── GameService.cs
    │   │   ├── IDeveloperService.cs
    │   │   └── DeveloperService.cs
    │   │
    │   ├── Exceptions/
    │   │   └── ...
    │   │
    │   └── Migrations/
    │       └── ...
    │
    └── GameCatalog.Tests/
        ├── GameApiTests.cs
        └── Infrastructure/
            ├── GameCatalogApiFactory.cs
            └── IntegrationTestFixture.cs
plaintext
Features/
├── Games/
│   ├── Game.cs
│   ├── GameEndpoints.cs
│   ├── GameService.cs
│   └── Dtos/
│
└── Developers/
    ├── Developer.cs
    ├── DeveloperEndpoints.cs
    ├── DeveloperService.cs
    └── Dtos/

An interface earns its place when it describes a useful contract, supports distinct implementations, or defines a boundary you need to control. This tutorial keeps service interfaces for comparison with ports and adapters. The integration tests can also run against concrete services registered directly in DI.

flowchart TD
    Client["Client or Scalar"] --> Api["Minimal API endpoint"]
    Api --> App["Validation and application service"]
    App --> EF["EF Core and Npgsql"]
    EF --> Pg[("Catalog PostgreSQL")]
    Api --> Error["Exception handler"]
    Error --> Response["Problem Details"]
    Tests["xUnit and WebApplicationFactory"] --> Api
    Tests --> Setup["Testcontainers and Respawn"]
    Setup --> TestDb[("Test PostgreSQL")]
    EF -.->|test configuration| TestDb

Docker commands and troubleshooting

From the GameCatalog root, use these commands to build, start, inspect, and stop the tutorial. Stop the foreground API with Ctrl+C before restarting it or running another container that publishes the same port.

powershell
docker compose run --rm --no-deps api dotnet build GameCatalog.slnx
docker compose run --rm api dotnet ef database update --project src/GameCatalog.Api
docker compose run --rm --service-ports api dotnet run --no-launch-profile --project src/GameCatalog.Api --urls http://0.0.0.0:8080

# In a separate terminal:
curl.exe -i http://localhost:8080/openapi/v1.json
curl.exe -i http://localhost:8080/games
docker compose exec db psql -U postgres -d gamecatalog -c "\dt"

# After stopping the API:
docker compose down

If the API starts but a query fails with 42P01, check the database name and migrations. If Scalar returns 404, check ASPNETCORE_ENVIRONMENT and the endpoint registration. If a GET route fails with a body-inference error, compare its service parameter type to the DI registration. For a database connection error, check whether the caller is on the Compose network, Windows, or the test runner before choosing a host name.

Official references

ASP.NET Core validation

Minimal API parameter binding

Managing EF Core migrations

Pagination with EF Core

PostgreSQL Docker Official Image

Testcontainers inside a container

Diagram
100%