Skip to content

Step 02 — Save orders with EF Core ​

What you'll do: add EF Core with PostgreSQL, create the orders tables with a migration, and add endpoints to place and read an order.

Steps ​

  1. Turn on central package management. Directory.Packages.props at the root holds every package version once, so two projects can never drift apart:

    xml
    <PropertyGroup>
      <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
    </PropertyGroup>
    <ItemGroup>
      <PackageVersion Include="EFCore.NamingConventions" Version="10.0.1" />
      <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
      <PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.4" />
    </ItemGroup>

    Orders.Api.csproj then lists the packages without versions:

    xml
    <PackageReference Include="EFCore.NamingConventions" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design">
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
  2. Install the EF Core command-line tool as a local tool, pinned in dotnet-tools.json, so everyone runs the same version:

    bash
    dotnet new tool-manifest
    dotnet tool install dotnet-ef --version 10.0.15

    After a fresh clone, dotnet tool restore installs it.

  3. Add the model in src/Orders.Api/Orders/: an Order with a list of OrderLines.

    csharp
    public sealed class Order
    {
        public Guid Id { get; init; }
        public required string CustomerEmail { get; init; }
        public DateTimeOffset PlacedAt { get; init; }
        public List<OrderLine> Lines { get; init; } = [];
    }
  4. Add OrdersDbContext. Order lines are owned by their order: EF Core saves and loads them together, in their own order_lines table.

    csharp
    modelBuilder.Entity<Order>(order =>
    {
        order.HasKey(o => o.Id);
        order.Property(o => o.CustomerEmail).HasMaxLength(254);
        order.OwnsMany(o => o.Lines, line =>
        {
            line.ToTable("order_lines");
            line.Property(l => l.Sku).HasMaxLength(32);
        });
    });
  5. Add the local connection string to appsettings.Development.json. It points at the container from step 01 (host port 5433):

    json
    "ConnectionStrings": {
      "Orders": "Host=localhost;Port=5433;Database=orders;Username=postgres;Password=postgres"
    }

    This password only exists in your local container. For a real server, keep the connection string out of the repo: use dotnet user-secrets on your machine and Azure Key Vault (or your platform's secret store) in production. appsettings.json has no connection string at all, so a misconfigured deployment fails at startup with a clear message.

  6. Register EF Core, ProblemDetails and validation in Program.cs:

    csharp
    builder.Services.AddProblemDetails();
    builder.Services.AddValidation();
    builder.Services.AddSingleton(TimeProvider.System);
    
    builder.Services.AddDbContext<OrdersDbContext>(options => options
        .UseNpgsql(builder.Configuration.GetConnectionString("Orders")
            ?? throw new InvalidOperationException("Connection string 'Orders' is missing."))
        .UseSnakeCaseNamingConvention());
    
    var app = builder.Build();
    
    app.UseExceptionHandler();
    app.UseStatusCodePages();
    
    if (app.Environment.IsDevelopment())
    {
        await using var scope = app.Services.CreateAsyncScope();
        await scope.ServiceProvider.GetRequiredService<OrdersDbContext>().Database.MigrateAsync();
    }
  7. Describe the request with validation attributes in PlaceOrderRequest.cs:

    csharp
    public sealed record PlaceOrderRequest(
        [property: Required, EmailAddress, MaxLength(254)] string CustomerEmail,
        [property: Required, MinLength(1), MaxLength(50)] List<PlaceOrderLine> Items);
    
    public sealed record PlaceOrderLine(
        [property: Required, RegularExpression("^[A-Z0-9-]{1,32}$")] string Sku,
        [property: Range(1, 100)] int Quantity);
  8. Add the endpoints in OrderEndpoints.cs and call app.MapOrderEndpoints() in Program.cs:

    csharp
    var order = new Order
    {
        Id = Guid.CreateVersion7(),
        CustomerEmail = request.CustomerEmail,
        PlacedAt = clock.GetUtcNow(),
        Lines = [.. request.Items.Select(i => new OrderLine { Sku = i.Sku, Quantity = i.Quantity })],
    };
    
    db.Orders.Add(order);
    await db.SaveChangesAsync(ct);
    
    return TypedResults.CreatedAtRoute(OrderResponse.From(order), nameof(GetOrder), new { id = order.Id });

    The API returns an OrderResponse, never the entity itself, so the database shape can change without breaking callers.

  9. Create the first migration:

    bash
    dotnet ef migrations add InitialCreate --project src/Orders.Api --output-dir Data/Migrations

Check it works ​

bash
docker compose up -d --wait
dotnet build OutboxInbox.slnx -warnaserror
dotnet run --project src/Orders.Api

Place an order:

bash
curl -i -X POST localhost:5080/orders -H 'content-type: application/json' \
  -d '{"customerEmail":"alex@contoso.com","items":[{"sku":"BOOK-1","quantity":2}]}'
HTTP/1.1 201 Created
Location: http://localhost:5080/orders/01a21a86-81e6-7bca-9a2e-059cfe1056f2

{"id":"01a21a86-81e6-7bca-9a2e-059cfe1056f2","customerEmail":"alex@contoso.com","placedAt":"2026-11-27T01:02:32.422474+00:00","items":[{"sku":"BOOK-1","quantity":2}]}

curl the Location URL to read it back (200). An unknown id returns 404 with a application/problem+json body. Send bad input:

bash
curl -i -X POST localhost:5080/orders -H 'content-type: application/json' \
  -d '{"customerEmail":"not-an-email","items":[{"sku":"book 1","quantity":0}]}'
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json

{"title":"One or more validation errors occurred.","status":400,"errors":{
  "CustomerEmail":["The CustomerEmail field is not a valid e-mail address."],
  "Items[0].Sku":["The field Sku must match the regular expression '^[A-Z0-9-]{1,32}$'."],
  "Items[0].Quantity":["The field Quantity must be between 1 and 100."]}}

Look at the tables:

bash
docker compose exec postgres psql -U postgres -d orders -c "select * from order_lines"
               order_id               | id |  sku   | quantity
--------------------------------------+----+--------+----------
 01a21a86-81e6-7bca-9a2e-059cfe1056f2 |  1 | BOOK-1 |        2

Why it works ​

EF Core and Npgsql. EF Core is .NET's object-relational mapper: you work with C# objects and it writes the SQL. Npgsql is the PostgreSQL driver and EF Core provider. UseSnakeCaseNamingConvention() (from EFCore.NamingConventions) maps CustomerEmail to customer_email, the usual PostgreSQL style, which keeps hand-written SQL readable later.

Migrations. A migration is a C# file that describes a schema change. dotnet ef migrations add compares your model with the last snapshot and writes the difference. Database.MigrateAsync() at startup applies pending migrations. That is handy on your laptop, but with several instances they would race each other, so it only runs in Development. For real deployments, build a migration bundle (dotnet ef migrations bundle) and run it once in your release pipeline before the new version starts.

Validation and ProblemDetails. AddValidation() is new in .NET 10: minimal APIs now check data annotations on request types, including nested lists, and return 400 before your handler runs. ProblemDetails (RFC 9457) is the standard JSON shape for HTTP errors. AddProblemDetails(), UseExceptionHandler() and UseStatusCodePages() make every error, from validation to an unhandled exception, use it, without leaking stack traces.

Version 7 GUIDs and TimeProvider. Guid.CreateVersion7() makes ids that sort by creation time, so inserts append to the primary key index instead of landing at random places. TimeProvider is .NET's injectable clock; code that asks it for the time can be tested with a fake clock instead of DateTimeOffset.UtcNow.

So far, saving an order is one plain database write. The next step adds the event that other services need to hear about, and shows why sending it is harder than it looks.

MIT licensed. Every step is a commit: git checkout step-01.