Skip to main content

Web frameworks · Intermediate · 32 min

Store data in an ASP.NET Core API with Entity Framework Core

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · .NET 10 LTS SDK (runtime 10.0.15) · EF Core 10.0.15 · xUnit v3 4.0.3 · mcr.microsoft.com/dotnet/sdk:10.0

You will give an ASP.NET Core minimal API a SQLite database through EF Core 10, with migrations, tracked and untracked queries, logged SQL, a version token that turns lost updates into 409 responses, and xUnit tests that each run against a fresh database.

On this page

An API that keeps its data in a list in memory forgets everything when it restarts. In this tutorial you give a small ASP.NET Core API a real database. You use Entity Framework Core (EF Core) 10, the object-relational mapper that ships with .NET: you write C# classes, EF Core turns them into tables, turns your LINQ queries into SQL, and turns the rows back into objects.

The API is a lending shelf for a reading club. It stores books and loans, lets members borrow a copy, and refuses to lend a copy that is not there, even when two people press "borrow" at the same moment. You use SQLite, a database in a single file, so there is nothing to install or run beside the API. The last steps show how the same code moves to PostgreSQL.

The project starts from an empty folder, so you can follow along without the code from the minimal API tutorial. That tutorial covers route groups, typed results, validation and OpenAPI in more depth; here the endpoints stay short so the database work stays in view. Everything uses .NET 10, the current long-term support release.

Step 1 · Create the API and add EF Core

Make a folder for the demo, create an empty web project in it, and install dotnet-ef, the command-line tool that creates and applies migrations. Installing it as a local tool records its version in a manifest file in the demo folder, so everyone who clones the project gets the same version with dotnet tool restore:

Bash
mkdir -p ~/efcore-shelf-demo
cd ~/efcore-shelf-demo
dotnet new web -n Shelf.Api -o Shelf.Api
dotnet new tool-manifest
dotnet tool install --local dotnet-ef --version 10.0.15

Now add two packages to the API project. Microsoft.EntityFrameworkCore.Sqlite is EF Core plus its SQLite provider. Microsoft.EntityFrameworkCore.Design holds the code dotnet-ef needs at design time; it is only used by the tool and is not part of what you deploy:

Bash
cd Shelf.Api
dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 10.0.15
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.15

The versions are pinned so a new EF Core release cannot change behaviour under you. EF Core 10 is the release that matches .NET 10; newer majors may need a newer runtime, so pin the version.

Check it worked

Bash
dotnet ef --version
dotnet list package

The first command prints Entity Framework Core .NET Command-line Tools and the version, 10.0.15. The local tool works from Shelf.Api because dotnet looks for the manifest in the current folder and its parents. The package list shows both EF Core packages at 10.0.15.

Step 2 · Describe the data with entity classes and a DbContext

An entity is a plain class that EF Core maps to a table. Create Models.cs with two of them:

Bash
cat > Models.cs <<'CS'
using System.ComponentModel.DataAnnotations;

namespace Shelf.Api;

public class Book
{
    public int Id { get; set; }

    [MaxLength(200)]
    public required string Title { get; set; }

    [MaxLength(120)]
    public required string Author { get; set; }

    public int CopiesAvailable { get; set; }

    [ConcurrencyCheck]
    public Guid Version { get; set; }

    public List<Loan> Loans { get; set; } = [];
}

public class Loan
{
    public int Id { get; set; }

    public int BookId { get; set; }
    public Book? Book { get; set; }

    [MaxLength(120)]
    public required string Borrower { get; set; }

    public DateTime LoanedAtUtc { get; set; }
}
CS

EF Core reads a lot from the shape of the classes:

  • A property called Id becomes the primary key, and an integer key is generated by the database.
  • string with nullable reference types on (the template turns them on) means the column is NOT NULL. string? would allow NULL.
  • List<Loan> Loans on Book, with BookId and Book on Loan, is a one-to-many relationship: one book, many loans. BookId becomes a foreign key.
  • [MaxLength] sets the column length in databases that enforce it. SQLite stores all text as TEXT and ignores the length, so the endpoints check lengths too.
  • [ConcurrencyCheck] on Version makes it a concurrency token. You use it in a later step to stop two requests overwriting each other.

Next, the DbContext: the class your code talks to. It knows the model, opens connections, tracks the objects you load and writes your changes back. Create ShelfDb.cs:

Bash
cat > ShelfDb.cs <<'CS'
using Microsoft.EntityFrameworkCore;

namespace Shelf.Api;

public class ShelfDb(DbContextOptions<ShelfDb> options) : DbContext(options)
{
    public DbSet<Book> Books => Set<Book>();
    public DbSet<Loan> Loans => Set<Loan>();
}
CS

Each DbSet<T> is a table you can query. The constructor takes its options from dependency injection, so the context does not know which database it is talking to. That is decided in Program.cs. Replace the template's Program.cs with this:

Bash
cat > Program.cs <<'CS'
using Microsoft.EntityFrameworkCore;
using Shelf.Api;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShelfDb>((services, options) =>
{
    var connectionString = services.GetRequiredService<IConfiguration>().GetConnectionString("Shelf")
        ?? throw new InvalidOperationException("Set the connection string ConnectionStrings:Shelf.");
    options.UseSqlite(connectionString);

    if (services.GetRequiredService<IHostEnvironment>().IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
    }
});

var app = builder.Build();

app.Run();
CS

AddDbContext registers ShelfDb with a scoped lifetime: each HTTP request gets its own context, disposed when the request ends. The connection string is read inside the lambda, when a context is first needed, rather than while the app starts. That small choice lets the tests later swap in their own database. EnableSensitiveDataLogging adds parameter values to the SQL logs, which helps while developing; it is only turned on in the Development environment because those values can be personal data. In .NET 10 the web SDK generates a public partial class Program for the top-level statements in Program.cs, so the test project can refer to the app without any extra code.

Finally, the configuration. Replace both settings files. The connection string lives in appsettings.json, and the log level for EF Core's SQL commands is Warning (off) by default and Information (on) in Development:

Bash
cat > appsettings.json <<'JSON'
{
  "ConnectionStrings": {
    "Shelf": "Data Source=shelf.db"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Warning"
    }
  },
  "AllowedHosts": "*"
}
JSON
cat > appsettings.Development.json <<'JSON'
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}
JSON

Data Source=shelf.db is a file in the folder the app runs from. It holds no secret, so it can sit in the settings file. A connection string with a password never goes in a committed file; the PostgreSQL step shows where it goes instead.

Check it worked

Bash
dotnet build

The build ends with Build succeeded and no errors. If you see CS9035 about a required member, a new Book or new Loan somewhere is missing Title, Author or Borrower.

Step 3 · Create the database with a migration

A migration is a C# file that describes how to change the database schema from one version of your model to the next. EF Core compares your classes with a snapshot of the last migration and writes the difference for you. Create the first one:

Bash
dotnet ef migrations add InitialCreate

The tool builds the project, starts the app far enough to read the ShelfDb registration, and writes three files to a new Migrations folder: <timestamp>_InitialCreate.cs with Up and Down methods, a designer file, and ShelfDbModelSnapshot.cs, the model as it stands now. Open the first file: Up calls CreateTable for Books and Loans and creates an index on Loans.BookId. Commit the Migrations folder with your code; it is the history of your schema.

Apply it:

Bash
dotnet ef database update

This creates shelf.db, runs Up, and records the migration's name in a table called __EFMigrationsHistory, so the same migration never runs twice.

Check it worked

Bash
dotnet ef migrations list
ls shelf.db

The list shows one line ending in _InitialCreate, with no (Pending) after it, which would mean it exists in code but has not been applied. ls shows shelf.db.

Step 4 · Write the endpoints and watch the SQL EF Core sends

Create BookEndpoints.cs. It holds the request and response records and five endpoints under /books:

Bash
cat > BookEndpoints.cs <<'CS'
using Microsoft.EntityFrameworkCore;

namespace Shelf.Api;

public record BookInput(string Title, string Author, int CopiesAvailable);
public record BookUpdate(string Title, string Author, int CopiesAvailable, Guid Version);
public record LoanInput(string Borrower);
public record BookView(int Id, string Title, string Author, int CopiesAvailable, Guid Version);
public record BookDetail(int Id, string Title, string Author, int CopiesAvailable, Guid Version, List<string> Borrowers);

public static class BookEndpoints
{
    public static void MapBookEndpoints(this IEndpointRouteBuilder app)
    {
        var books = app.MapGroup("/books");

        books.MapGet("/", async (string? author, ShelfDb db) =>
        {
            var query = db.Books.AsQueryable();
            if (!string.IsNullOrWhiteSpace(author))
            {
                query = query.Where(b => b.Author == author);
            }

            return await query
                .OrderBy(b => b.Title)
                .Select(b => new BookView(b.Id, b.Title, b.Author, b.CopiesAvailable, b.Version))
                .ToListAsync();
        });

        books.MapGet("/{id:int}", async (int id, ShelfDb db) =>
        {
            var book = await db.Books
                .AsNoTracking()
                .Include(b => b.Loans)
                .FirstOrDefaultAsync(b => b.Id == id);

            if (book is null) return Results.NotFound();

            var borrowers = book.Loans.OrderBy(l => l.LoanedAtUtc).Select(l => l.Borrower).ToList();
            return Results.Ok(new BookDetail(book.Id, book.Title, book.Author, book.CopiesAvailable, book.Version, borrowers));
        });

        books.MapPost("/", async (BookInput input, ShelfDb db) =>
        {
            if (Check(input.Title, input.Author, input.CopiesAvailable) is { } invalid) return invalid;

            var book = new Book
            {
                Title = input.Title.Trim(),
                Author = input.Author.Trim(),
                CopiesAvailable = input.CopiesAvailable,
                Version = Guid.NewGuid(),
            };
            db.Books.Add(book);
            await db.SaveChangesAsync();

            return Results.Created($"/books/{book.Id}", ToView(book));
        });

        books.MapPut("/{id:int}", async (int id, BookUpdate input, ShelfDb db) =>
        {
            if (Check(input.Title, input.Author, input.CopiesAvailable) is { } invalid) return invalid;

            var book = await db.Books.FindAsync(id);
            if (book is null) return Results.NotFound();

            // Compare against the version the client last saw, not the one just loaded.
            db.Entry(book).Property(b => b.Version).OriginalValue = input.Version;

            book.Title = input.Title.Trim();
            book.Author = input.Author.Trim();
            book.CopiesAvailable = input.CopiesAvailable;
            book.Version = Guid.NewGuid();

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                return Conflict("This book changed after you loaded it. Load it again and reapply your change.");
            }

            return Results.Ok(ToView(book));
        });

        books.MapPost("/{id:int}/loans", async (int id, LoanInput input, ShelfDb db) =>
        {
            if (string.IsNullOrWhiteSpace(input.Borrower) || input.Borrower.Trim().Length > 120)
            {
                return Results.ValidationProblem(new Dictionary<string, string[]>
                {
                    ["borrower"] = ["Give a borrower name of 1 to 120 characters."],
                });
            }

            var book = await db.Books.FindAsync(id);
            if (book is null) return Results.NotFound();
            if (book.CopiesAvailable == 0) return Conflict("No copies of this book are available.");

            book.CopiesAvailable -= 1;
            book.Version = Guid.NewGuid();
            book.Loans.Add(new Loan { Borrower = input.Borrower.Trim(), LoanedAtUtc = DateTime.UtcNow });

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                return Conflict("Someone else changed this book at the same moment. Try again.");
            }

            return Results.Created($"/books/{book.Id}", ToView(book));
        });
    }

    static BookView ToView(Book b) => new(b.Id, b.Title, b.Author, b.CopiesAvailable, b.Version);

    static IResult Conflict(string detail) =>
        Results.Problem(statusCode: StatusCodes.Status409Conflict, title: "Conflict", detail: detail);

    static IResult? Check(string? title, string? author, int copies)
    {
        var errors = new Dictionary<string, string[]>();
        if (string.IsNullOrWhiteSpace(title) || title.Trim().Length > 200)
            errors["title"] = ["Give a title of 1 to 200 characters."];
        if (string.IsNullOrWhiteSpace(author) || author.Trim().Length > 120)
            errors["author"] = ["Give an author of 1 to 120 characters."];
        if (copies < 0)
            errors["copiesAvailable"] = ["Copies cannot be negative."];
        return errors.Count == 0 ? null : Results.ValidationProblem(errors);
    }
}
CS

The reading endpoints show the three ways to get data out:

  • A projection. GET /books builds a LINQ query, adds a Where only when ?author= is given, and ends with Select into a BookView. EF Core translates the whole chain into one SELECT that fetches only those five columns. ToListAsync is the point where the SQL runs; until then, query is only a description. Projected records are not entities, so EF Core never tracks them.
  • An untracked load. GET /books/{id} loads a whole Book entity with its loans (Include adds a join). Normally the context tracks every entity it loads: it keeps a copy of the original values so SaveChanges can work out what changed. This endpoint only reads, so AsNoTracking() skips that bookkeeping, which saves memory and time on every read-only query.
  • A tracked load. PUT and the loans endpoint use FindAsync, which returns a tracked entity. You change its properties and call SaveChangesAsync; EF Core compares them with the originals and sends an UPDATE for only the changed columns. In the loans endpoint, the new Loan and the changed Book are saved together in one transaction, so a loan is never recorded without the copy count going down.

The author value from the query string never becomes part of the SQL text. EF Core sends it as a parameter, which is what keeps LINQ queries safe from SQL injection.

Now wire the endpoints into the app. Replace Program.cs again; the only changes are the two lines for problem details and the endpoints:

Bash
cat > Program.cs <<'CS'
using Microsoft.EntityFrameworkCore;
using Shelf.Api;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShelfDb>((services, options) =>
{
    var connectionString = services.GetRequiredService<IConfiguration>().GetConnectionString("Shelf")
        ?? throw new InvalidOperationException("Set the connection string ConnectionStrings:Shelf.");
    options.UseSqlite(connectionString);

    if (services.GetRequiredService<IHostEnvironment>().IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
    }
});
builder.Services.AddProblemDetails();

var app = builder.Build();

app.MapBookEndpoints();

app.Run();
CS

Start the API in your second terminal, from the Shelf.Api folder, and leave it running. dotnet run uses the Development environment from the project's launch settings:

Bash
dotnet run --urls http://127.0.0.1:5080

It logs Now listening on: http://127.0.0.1:5080. Back in your first terminal, add three books and one that is not valid:

Bash
curl -s -X POST http://127.0.0.1:5080/books -H 'Content-Type: application/json' \
  -d '{"title":"Things Fall Apart","author":"Chinua Achebe","copiesAvailable":2}'
echo
curl -s -X POST http://127.0.0.1:5080/books -H 'Content-Type: application/json' \
  -d '{"title":"Arrow of God","author":"Chinua Achebe","copiesAvailable":1}'
echo
curl -s -X POST http://127.0.0.1:5080/books -H 'Content-Type: application/json' \
  -d '{"title":"Ògbójú Ọdẹ nínú Igbó Irúnmalẹ̀","author":"D. O. Fágúnwà","copiesAvailable":1}'
echo
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:5080/books -H 'Content-Type: application/json' \
  -d '{"title":"","author":"Nobody","copiesAvailable":1}'

The third title is Yoruba, with tone marks. SQLite and PostgreSQL store text as UTF-8, so it is saved exactly as typed. The JSON response returns them unchanged too: ASP.NET Core configures its JSON serialiser with a relaxed encoder, so letters such as Ò are written as UTF-8 rather than as \u00D2 escapes, which is what plain System.Text.Json would do by default.

Check it worked

Each of the first three requests prints the new book, starting {"id":1,"title":"Things Fall Apart", then ids 2 and 3, each with its own version GUID. The empty title prints 400. Filter by author:

Bash
curl -s 'http://127.0.0.1:5080/books?author=Chinua%20Achebe' | grep -o '"title":"[^"]*"'

You see two lines in title order: "title":"Arrow of God" then "title":"Things Fall Apart".

Now look at the terminal running the API. Each request logged an info: Microsoft.EntityFrameworkCore.Database.Command[20101] entry with Executed DbCommand, the time it took, the parameter values and the SQL. The author filter looks something like this, with the column list shortened:

Text
Executed DbCommand (1ms) [Parameters=[@author='Chinua Achebe' (Size = 13)], CommandType='Text', CommandTimeout='30']
SELECT "b"."Id", "b"."Title", "b"."Author", ...
FROM "Books" AS "b"
WHERE "b"."Author" = @author
ORDER BY "b"."Title"

Reading this log is the quickest way to catch a query that does more than you meant, such as one SELECT per row in a loop. In production the level stays at Warning, so neither the SQL nor the values are written.

Step 5 · Turn a lost update into a 409 conflict

Two librarians open the same book. One changes the copy count to 3, the other to 5 a moment later, both starting from the same data. Without protection the second save silently overwrites the first. This is a lost update.

The Version token prevents it. Because it is marked [ConcurrencyCheck], every UPDATE EF Core sends for a book includes it in the WHERE clause: "update book 2, but only if its version is still the one I started with". Each successful change also sets a new GUID. If someone else saved in between, the version no longer matches, no row is updated, and EF Core throws DbUpdateConcurrencyException, which the endpoints turn into 409 Conflict. In PUT, the line that sets OriginalValue makes the check use the version the client sent, which is what the client actually saw.

Read the version of book 2, then send two updates that both start from it:

Bash
VERSION=$(curl -s http://127.0.0.1:5080/books/2 | grep -o '"version":"[^"]*"' | cut -d'"' -f4)
echo "$VERSION"
curl -s -o /dev/null -w '%{http_code}\n' -X PUT http://127.0.0.1:5080/books/2 -H 'Content-Type: application/json' \
  -d "{\"title\":\"Arrow of God\",\"author\":\"Chinua Achebe\",\"copiesAvailable\":3,\"version\":\"$VERSION\"}"
curl -s -o /dev/null -w '%{http_code}\n' -X PUT http://127.0.0.1:5080/books/2 -H 'Content-Type: application/json' \
  -d "{\"title\":\"Arrow of God\",\"author\":\"Chinua Achebe\",\"copiesAvailable\":5,\"version\":\"$VERSION\"}"
curl -s http://127.0.0.1:5080/books/2 | grep -o '"copiesAvailable":[0-9]*'

The loans endpoint relies on the same token without the client sending anything. It loads the book, checks that a copy is left, and saves the new count with the version it loaded. If two members borrow the last copy at the same instant, both see 1 copy, but only the first UPDATE matches the version; the second gets a 409 and nobody is lent a copy that does not exist. Borrow the one copy of book 3 twice:

Bash
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:5080/books/3/loans -H 'Content-Type: application/json' -d '{"borrower":"Amaka"}'
curl -s -X POST http://127.0.0.1:5080/books/3/loans -H 'Content-Type: application/json' -d '{"borrower":"Kwame"}'
echo
curl -s http://127.0.0.1:5080/books/3 | grep -oE '"copiesAvailable":[0-9]+|"borrowers":\[[^]]*\]'

SQLite cannot generate a new version for you, so the code sets a fresh GUID on every change. SQL Server can with a rowversion column, and PostgreSQL has a built-in xmin column that Npgsql can use the same way; the GUID approach works on all of them.

Check it worked

The version is a GUID such as 3f2b0c1e-.... The first PUT prints 200 and the second 409, and the stored count is "copiesAvailable":3: the first change was kept and the second was refused instead of overwriting it. A client that gets a 409 should load the book again and show the person the current values.

The first loan prints 201. The second prints a problem response with "status":409 and "detail":"No copies of this book are available.". Book 3 now shows "copiesAvailable":0 and "borrowers":["Amaka"].

Step 6 · Change the schema with a second migration, and restart

The ?author= filter has to read every row of Books to find matches. With a few thousand books that is noticeable, so add an index on Author. Stop the API with Ctrl+C in the second terminal first, so the build can replace its files.

Indexes are configured in OnModelCreating, EF Core's place for anything attributes do not cover. Replace ShelfDb.cs:

Bash
cat > ShelfDb.cs <<'CS'
using Microsoft.EntityFrameworkCore;

namespace Shelf.Api;

public class ShelfDb(DbContextOptions<ShelfDb> options) : DbContext(options)
{
    public DbSet<Book> Books => Set<Book>();
    public DbSet<Loan> Loans => Set<Loan>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Book>().HasIndex(b => b.Author);
    }
}
CS
dotnet ef migrations add AddAuthorIndex

Before applying a migration to a database that matters, look at the SQL it will run. migrations script prints it without touching the database:

Bash
dotnet ef migrations script InitialCreate AddAuthorIndex

Then apply it:

Bash
dotnet ef database update

Start the API again in the second terminal with the same dotnet run command.

Bash
dotnet ef migrations list
curl -s http://127.0.0.1:5080/books | grep -o '"id":[0-9]*' | wc -l
curl -s http://127.0.0.1:5080/books/3 | grep -o '"borrowers":\[[^]]*\]'

To see what the index does to a query plan on PostgreSQL, work through speed up slow PostgreSQL queries with EXPLAIN.

Check it worked

The script contains a CREATE INDEX "IX_Books_Author" ON "Books" ("Author"); statement and an INSERT into __EFMigrationsHistory. The migration list shows two names, ..._InitialCreate and ..._AddAuthorIndex, neither marked (Pending). After the restart the API still has 3 books, and book 3 still shows "borrowers":["Amaka"]: the data came back from shelf.db.

Step 7 · Test the API against a fresh database

Tests must not depend on the data you typed by hand, or on each other. Each test here gets a brand-new SQLite file with the migrations applied, starts the API in memory with WebApplicationFactory, and deletes the file afterwards.

Create the test project next to the API. It uses xUnit v3, whose test projects are small programs you can start with dotnet run, and Microsoft.AspNetCore.Mvc.Testing, which hosts the API inside the test process:

Bash
cd ~/efcore-shelf-demo
mkdir -p Shelf.Tests
cat > Shelf.Tests/Shelf.Tests.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <OutputType>Exe</OutputType>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.15" />
    <PackageReference Include="xunit.v3" Version="4.0.3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="../Shelf.Api/Shelf.Api.csproj" />
  </ItemGroup>

</Project>
XML

Now the tests. The constructor runs before each test: it points the app's ConnectionStrings:Shelf at a new temporary file, then uses the app's own ShelfDb to apply the migrations, the same ones you applied by hand. Because Program.cs reads the connection string only when a context is created, the test's value is the one used:

Bash
cat > Shelf.Tests/BookApiTests.cs <<'CS'
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Shelf.Api;
using Xunit;

namespace Shelf.Tests;

public sealed class BookApiTests : IDisposable
{
    private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"shelf-test-{Guid.NewGuid():N}.db");
    private readonly WebApplicationFactory<Program> _factory;
    private readonly HttpClient _client;

    private static CancellationToken Ct => TestContext.Current.CancellationToken;

    public BookApiTests()
    {
        _factory = new WebApplicationFactory<Program>().WithWebHostBuilder(web =>
            web.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["ConnectionStrings:Shelf"] = $"Data Source={_dbPath}",
            })));

        using (var scope = _factory.Services.CreateScope())
        {
            scope.ServiceProvider.GetRequiredService<ShelfDb>().Database.Migrate();
        }

        _client = _factory.CreateClient();
    }

    public void Dispose()
    {
        _client.Dispose();
        _factory.Dispose();
        SqliteConnection.ClearAllPools();
        File.Delete(_dbPath);
    }

    private async Task<BookView> AddBook(string title, string author, int copies)
    {
        var response = await _client.PostAsJsonAsync("/books", new BookInput(title, author, copies), Ct);
        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        return (await response.Content.ReadFromJsonAsync<BookView>(Ct))!;
    }

    [Fact]
    public async Task A_new_database_has_no_books()
    {
        var books = await _client.GetFromJsonAsync<List<BookView>>("/books", Ct);
        Assert.NotNull(books);
        Assert.Empty(books);
    }

    [Fact]
    public async Task Books_are_stored_and_filtered_by_author()
    {
        await AddBook("Things Fall Apart", "Chinua Achebe", 2);
        await AddBook("So Long a Letter", "Mariama Bâ", 1);

        var achebe = await _client.GetFromJsonAsync<List<BookView>>("/books?author=Chinua%20Achebe", Ct);
        var all = await _client.GetFromJsonAsync<List<BookView>>("/books", Ct);

        Assert.Equal(new[] { "Things Fall Apart" }, achebe!.Select(b => b.Title).ToArray());
        Assert.Equal(new[] { "So Long a Letter", "Things Fall Apart" }, all!.Select(b => b.Title).ToArray());
        Assert.Contains(all!, b => b.Author == "Mariama Bâ");
    }

    [Fact]
    public async Task An_update_from_a_stale_version_is_rejected()
    {
        var book = await AddBook("Arrow of God", "Chinua Achebe", 1);

        var first = await _client.PutAsJsonAsync($"/books/{book.Id}", new BookUpdate(book.Title, book.Author, 3, book.Version), Ct);
        var second = await _client.PutAsJsonAsync($"/books/{book.Id}", new BookUpdate(book.Title, book.Author, 5, book.Version), Ct);

        Assert.Equal(HttpStatusCode.OK, first.StatusCode);
        Assert.Equal(HttpStatusCode.Conflict, second.StatusCode);
        var stored = await _client.GetFromJsonAsync<BookDetail>($"/books/{book.Id}", Ct);
        Assert.Equal(3, stored!.CopiesAvailable);
    }

    [Fact]
    public async Task The_last_copy_can_only_be_lent_once()
    {
        var book = await AddBook("Half of a Yellow Sun", "Chimamanda Ngozi Adichie", 1);

        var first = await _client.PostAsJsonAsync($"/books/{book.Id}/loans", new LoanInput("Amaka"), Ct);
        var second = await _client.PostAsJsonAsync($"/books/{book.Id}/loans", new LoanInput("Kwame"), Ct);

        Assert.Equal(HttpStatusCode.Created, first.StatusCode);
        Assert.Equal(HttpStatusCode.Conflict, second.StatusCode);
        var stored = await _client.GetFromJsonAsync<BookDetail>($"/books/{book.Id}", Ct);
        Assert.Equal(0, stored!.CopiesAvailable);
        Assert.Equal("Amaka", Assert.Single(stored.Borrowers));
    }
}
CS
dotnet run --project Shelf.Tests

SqliteConnection.ClearAllPools() closes the connections EF Core keeps open for reuse, so the file can be deleted on every operating system. xUnit creates a new instance of the class for each test, which is why each test gets its own file.

Check it worked

The run builds both projects, prints the API's log lines as the tests call it, and ends with a summary along the lines of total: 4, failed: 0, succeeded: 4. Change Assert.Equal(3, ...) to 4 and run again to see a failure reported with the expected and actual values, then change it back.

The database you filled by hand is untouched:

Bash
curl -s http://127.0.0.1:5080/books | grep -o '"id":[0-9]*' | wc -l
find /tmp -maxdepth 1 -name 'shelf-test-*.db' | wc -l

The first line is still 3, and the second is 0: every test database was deleted. On macOS, Path.GetTempPath() is a folder under /var/folders, so check there instead of /tmp.

Step 8 · Point the API at PostgreSQL in production

SQLite suits development, tests and a small API on one server. For many simultaneous writers, or several servers sharing one database, use PostgreSQL. The entities, endpoints and tests stay the same; the provider and the connection string change. Set up a server, a role appuser and a database appdb with install PostgreSQL 18 on Ubuntu 26.04.

Before you switch provider, see how the connection string will reach the app. ASP.NET Core reads configuration from environment variables, with __ (two underscores) in place of :, and an environment variable wins over appsettings.json. While the app still uses SQLite, point it at a different file and apply the migrations there:

Bash
cd ~/efcore-shelf-demo/Shelf.Api
ConnectionStrings__Shelf='Data Source=staging.db' dotnet ef database update
ls staging.db
rm staging.db

A new staging.db appears, with both migrations applied, while shelf.db keeps your books. This only works with a SQLite connection string, so do it before the edits below.

Now switch provider. Add the Npgsql provider to the API project:

Bash
cd ~/efcore-shelf-demo/Shelf.Api
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version 10.0.3

In Program.cs, replace options.UseSqlite(connectionString); with:

C#
options.UseNpgsql(connectionString);

Keep the password out of settings files, the code and your shell history. Npgsql can read it from a PostgreSQL password file. Create the file private first, then add one line in your editor, in the form 127.0.0.1:5432:appdb:appuser:<your password> (replace <your password> with the one you set for appuser):

Bash
install -m 600 /dev/null ~/.pgpass
nano ~/.pgpass

Migrations are written for one provider: the SQLite ones use SQLite column types, and applying them to PostgreSQL gives the wrong schema or fails. For an app that runs only on PostgreSQL, the commands below delete the Migrations folder, including your two SQLite migrations, and create the first migration again for PostgreSQL before applying it. Commit or copy the folder first if you want to keep the SQLite history. Keep the tests on SQLite only if you are happy that they test a different database from production; many teams run them against a PostgreSQL container instead.

Bash
export ConnectionStrings__Shelf="Host=127.0.0.1;Port=5432;Database=appdb;Username=appuser;Passfile=$HOME/.pgpass"
rm -rf Migrations
dotnet ef migrations add InitialCreate
dotnet ef database update

The connection string now holds no secret, so it is safe in an environment variable. On a server, put the variable in the service's environment file rather than a shell profile.

Check it worked

The staging.db check earlier showed the environment variable winning over appsettings.json. With PostgreSQL configured, list the tables the migration created:

Bash
psql "host=127.0.0.1 dbname=appdb user=appuser" -c '\dt'

psql reads the password from ~/.pgpass too, and lists Books, Loans and __EFMigrationsHistory. The new Migrations folder holds a single ..._InitialCreate migration whose columns use PostgreSQL types such as integer and uuid.

Step 9 · Clean up

Stop the API with Ctrl+C in the second terminal.

Remove the demo folder, which holds both projects, the local tool manifest and the SQLite database. The .NET SDK and the NuGet package cache stay. If you tried the PostgreSQL step, also remove the line you added to ~/.pgpass and drop the tables in psql with DROP TABLE "Loans", "Books", "__EFMigrationsHistory";.

Bash
cd ~
rm -rf ~/efcore-shelf-demo

Check it worked

Bash
test ! -e ~/efcore-shelf-demo && echo "removed"

It prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.