Lab 2: Real Orders in a Real Database
45 minutes · Starts from checkpoint-1 · Ends at checkpoint-2
You replace the in-memory catalog with EF Core and SQLite, add customers and orders, validate input, and make every error look the same.
As in Lab 1, every path below is relative to src/Roastery.Api, and the requests live in http/module-2.http at the repo root. Run the API with dotnet run --launch-profile https.
Step 1: Add EF Core and the model
cd src/Roastery.Api
dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 10.0.11
dotnet add package Microsoft.EntityFrameworkCore.Design --version 10.0.11
These match the versions in the checkpoint-2 project file. Stay in src/Roastery.Api for the rest of the lab: dotnet ef looks for a project in the current directory and fails with "No project was found" anywhere else.
Add the remaining entities to Models/ (namespace Roastery.Api.Models):
public class Customer
{
public int Id { get; set; }
public required string Name { get; set; }
public required string Email { get; set; }
}
public enum OrderStatus { Pending, Roasting, Ready, PickedUp, Cancelled }
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Pending;
public decimal Total { get; set; }
public DateTimeOffset PlacedAt { get; set; }
public List<OrderLine> Lines { get; set; } = [];
}
public class OrderLine
{
public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}
Create Data/RoasteryDbContext.cs (copy it from the concepts page) and the configuration classes in Data/Configurations/. The rules they must encode:
- Enums as strings.
Product.RoastandOrder.StatususeHasConversion<string>().HasMaxLength(20), so the database holds"Pending", not0. - Lengths and money.
HasMaxLength(100)onProduct.NameandCustomer.Name,200onCustomer.Email;HasPrecision(10, 2)onPrice,Total, andUnitPrice. - Unique indexes on
Customer.EmailandProduct.Name. PlacedAtstored as UTC ticks. SQLite cannotORDER BYaDateTimeOffset, and Step 4 sorts by it.- Relationships.
Order→Customer,Order→Lines(cascade delete), andOrderLine→Product.OrderLineConfigurationlives inOrderConfiguration.csnext to its parent.
// Data/Configurations/ProductConfiguration.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Roastery.Api.Models;
namespace Roastery.Api.Data.Configurations;
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.Property(p => p.Name).HasMaxLength(100).IsRequired();
builder.Property(p => p.Roast).HasConversion<string>().HasMaxLength(20);
builder.Property(p => p.Price).HasPrecision(10, 2);
builder.HasIndex(p => p.Name).IsUnique();
}
}
// Data/Configurations/CustomerConfiguration.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Roastery.Api.Models;
namespace Roastery.Api.Data.Configurations;
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
builder.Property(c => c.Name).HasMaxLength(100).IsRequired();
builder.Property(c => c.Email).HasMaxLength(200).IsRequired();
builder.HasIndex(c => c.Email).IsUnique();
}
}
// Data/Configurations/OrderConfiguration.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Roastery.Api.Models;
namespace Roastery.Api.Data.Configurations;
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.Property(o => o.Total).HasPrecision(10, 2);
builder.Property(o => o.Status).HasConversion<string>().HasMaxLength(20);
// SQLite cannot sort DateTimeOffset columns; store UTC ticks so ORDER BY PlacedAt works.
builder.Property(o => o.PlacedAt)
.HasConversion(v => v.UtcTicks, v => new DateTimeOffset(v, TimeSpan.Zero));
builder.HasOne<Customer>().WithMany().HasForeignKey(o => o.CustomerId);
builder.HasMany(o => o.Lines).WithOne().HasForeignKey(l => l.OrderId).OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(o => new { o.CustomerId, o.PlacedAt });
}
}
public class OrderLineConfiguration : IEntityTypeConfiguration<OrderLine>
{
public void Configure(EntityTypeBuilder<OrderLine> builder)
{
builder.Property(l => l.UnitPrice).HasPrecision(10, 2);
builder.HasOne<Product>().WithMany().HasForeignKey(l => l.ProductId);
}
}
Write the configurations before you create the migration. The migration is a snapshot of the model as EF Core sees it at that moment: the column types, indexes, and foreign keys above are what end up in InitialCreate. Change them later and you need a second migration.
Set the connection string in appsettings.Development.json, and turn on EF Core's SQL logging while you are there so you can watch the queries:
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"ConnectionStrings": { "Roastery": "Data Source=roastery.db" }
Register the context in Program.cs (add using Microsoft.EntityFrameworkCore; and using Roastery.Api.Data;), then create the migration, named InitialCreate, and apply it:
builder.Services.AddDbContext<RoasteryDbContext>(o =>
o.UseSqlite(builder.Configuration.GetConnectionString("Roastery")));
dotnet ef migrations add InitialCreate
dotnet ef database update
roastery.db is created in src/Roastery.Api (the path is relative to the working directory) and is already in .gitignore.
Add the development-only MigrateAsync() and seed block from the concepts page to Program.cs, after builder.Build(). Then add Seed.RunAsync to the existing Data/Seed.cs. It loads the five Lab 1 products, the two customers, and one Pending order per customer: order 1 belongs to Sam (customer 1), order 2 to Jordan (customer 2).
warning Keep the seeded orders
Module 3 uses Jordan's order 2 as "someone else's order" to prove a customer cannot read it. Seed exactly one order per customer, and do not move order 2 through the lifecycle in this lab.
// Add to the top of Data/Seed.cs:
using Microsoft.EntityFrameworkCore;
using Roastery.Api.Models;
// Add inside the Seed class, below the Products and Customers arrays:
public static async Task RunAsync(RoasteryDbContext db, CancellationToken ct = default)
{
if (!await db.Products.AnyAsync(ct))
{
db.Products.AddRange(Products.Select(p => new Product
{
Name = p.Name, Roast = Enum.Parse<Roast>(p.Roast), Price = p.Price, StockQuantity = p.Stock
}));
}
if (!await db.Customers.AnyAsync(ct))
{
db.Customers.AddRange(Customers.Select(c => new Customer { Name = c.Name, Email = c.Email }));
}
await db.SaveChangesAsync(ct);
if (!await db.Orders.AnyAsync(ct))
{
// One order per seed customer so Module 3 has "someone else's order" to test against.
var products = await db.Products.OrderBy(p => p.Id).Take(2).ToListAsync(ct);
var customers = await db.Customers.OrderBy(c => c.Id).ToListAsync(ct);
foreach (var customer in customers)
{
var line = new OrderLine { ProductId = products[0].Id, Quantity = 1, UnitPrice = products[0].Price };
db.Orders.Add(new Order
{
CustomerId = customer.Id,
PlacedAt = DateTimeOffset.UtcNow.AddDays(-1),
Lines = [line],
Total = line.Quantity * line.UnitPrice
});
}
await db.SaveChangesAsync(ct);
}
}
Every block checks before it inserts, so restarting the app does not duplicate anything. The flip side: to get back to a clean database, stop the app, delete roastery.db (and roastery.db-shm / roastery.db-wal if present), and start it again. Startup re-applies the migration and re-seeds.
Step 2: Swap the catalog
Write Services/EfProductCatalog.cs : IProductCatalog backed by the DbContext, delete InMemoryProductCatalog, and change the registration from AddSingleton to AddScoped. Run every Lab 1 request again.
using Microsoft.EntityFrameworkCore;
using Roastery.Api.Contracts;
using Roastery.Api.Data;
using Roastery.Api.Models;
namespace Roastery.Api.Services;
public class EfProductCatalog(RoasteryDbContext db) : IProductCatalog
{
public async Task<IReadOnlyList<Product>> ListAsync(string? roast, bool? inStock, CancellationToken ct)
{
var query = db.Products.AsNoTracking();
if (roast is not null && Enum.TryParse<Roast>(roast, true, out var r))
query = query.Where(p => p.Roast == r);
if (inStock is true)
query = query.Where(p => p.StockQuantity > 0);
return await query.OrderBy(p => p.Id).ToListAsync(ct);
}
public Task<Product?> FindAsync(int id, CancellationToken ct) =>
db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == id, ct);
public async Task<Product> AddAsync(CreateProductRequest request, CancellationToken ct)
{
var product = new Product
{
Name = request.Name,
Roast = Enum.Parse<Roast>(request.Roast, true),
Price = request.Price,
StockQuantity = request.StockQuantity
};
db.Products.Add(product);
await db.SaveChangesAsync(ct);
return product;
}
}
// Program.cs
builder.Services.AddScoped<IProductCatalog, EfProductCatalog>();
success
Nothing in the HTTP contract changed. The endpoints, the DTOs, and the .http file are identical; only the implementation behind the interface moved. That separation is the reason Module 1 insisted on DTOs.
warning Product names are unique now
The "Create a product" request in module-1.http ("Kenya AA") works once. Send it again and the unique index on Product.Name rejects the insert, which surfaces as a 500. Change the name before you re-send it. Products now survive restarts, unlike in Lab 1.
Step 3: Place an order
Create Contracts/OrderContracts.cs with every contract the rest of the lab uses. The request records carry the annotations; CreateOrderRequest adds a cross-field rule with IValidatableObject. Validate only runs once the property annotations pass; the is not null guard is cheap insurance in case the record is validated some other way.
using System.ComponentModel.DataAnnotations;
namespace Roastery.Api.Contracts;
public record OrderLineRequest(
[property: Range(1, int.MaxValue)] int ProductId,
[property: Range(1, 50)] int Quantity);
public record CreateOrderRequest(
[property: Required, MinLength(1)] List<OrderLineRequest> Lines) : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Lines is not null && Lines.GroupBy(l => l.ProductId).Any(g => g.Count() > 1))
yield return new ValidationResult("Each product may appear only once.", [nameof(Lines)]);
}
}
public record ChangeOrderStatusRequest([property: Required] string Status);
public record OrderLineDto(int ProductId, int Quantity, decimal UnitPrice, decimal LineTotal);
public record OrderDto(int Id, int CustomerId, string Status, decimal Total, DateTimeOffset PlacedAt,
IReadOnlyList<OrderLineDto> Lines);
public record OrderSummaryDto(int Id, int CustomerId, string Status, decimal Total, DateTimeOffset PlacedAt);
/// <summary>Query-string paging and filtering for the order list.</summary>
public record OrderQuery(int Page = 1, int PageSize = 20, string? Status = null);
public record PagedResult<T>(IReadOnlyList<T> Items, int Page, int PageSize, int TotalCount);
Add the order mapping next to the product one in Contracts/Mapping.cs:
public static OrderDto ToDto(this Order o) =>
new(o.Id, o.CustomerId, o.Status.ToString(), o.Total, o.PlacedAt,
o.Lines.Select(l => new OrderLineDto(l.ProductId, l.Quantity, l.UnitPrice, l.Quantity * l.UnitPrice)).ToList());
Turn on validation and the ProblemDetails service in Program.cs, and register the clock (Module 4's tests swap it for a fake):
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddValidation();
builder.Services.AddProblemDetails();
Create Endpoints/OrderEndpoints.cs with a /api/orders group and implement POST /. It needs these usings:
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using Roastery.Api.Contracts;
using Roastery.Api.Data;
using Roastery.Api.Domain;
using Roastery.Api.Models;
static async Task<Results<CreatedAtRoute<OrderDto>, ValidationProblem>> CreateOrder(
CreateOrderRequest request, RoasteryDbContext db, TimeProvider clock, CancellationToken ct)
{
var ids = request.Lines.Select(l => l.ProductId).ToList();
var products = await db.Products.Where(p => ids.Contains(p.Id)).ToDictionaryAsync(p => p.Id, ct);
var errors = new Dictionary<string, string[]>();
foreach (var (line, i) in request.Lines.Select((l, i) => (l, i)))
{
if (!products.TryGetValue(line.ProductId, out var product))
errors[$"Lines[{i}].ProductId"] = ["Unknown product."];
else if (product.StockQuantity < line.Quantity)
errors[$"Lines[{i}].Quantity"] = [$"Only {product.StockQuantity} in stock."];
}
if (errors.Count > 0) return TypedResults.ValidationProblem(errors);
var order = new Order
{
CustomerId = 1, // replaced by the token's customer_id claim in Module 3
PlacedAt = clock.GetUtcNow(),
Lines = request.Lines.Select(l => new OrderLine
{
ProductId = l.ProductId, Quantity = l.Quantity, UnitPrice = products[l.ProductId].Price
}).ToList()
};
order.Total = order.Lines.Sum(l => l.Quantity * l.UnitPrice);
foreach (var line in order.Lines) products[line.ProductId].StockQuantity -= line.Quantity;
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
return TypedResults.CreatedAtRoute(order.ToDto(), "GetOrder", new { id = order.Id });
}
Add GET /{id:int} named GetOrder (Include the lines, return NotFound when missing), and call app.MapOrderEndpoints() in Program.cs.
namespace Roastery.Api.Endpoints;
public static class OrderEndpoints
{
public static RouteGroupBuilder MapOrderEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/api/orders").WithTags("Orders");
group.MapGet("/", ListOrders).WithName("ListOrders").WithSummary("List orders, paged.");
group.MapGet("/{id:int}", GetOrder).WithName("GetOrder");
group.MapPost("/", CreateOrder).WithName("CreateOrder").WithSummary("Place an order.");
group.MapPut("/{id:int}/status", ChangeStatus).WithName("ChangeOrderStatus")
.WithSummary("Advance an order through its lifecycle.");
return group;
}
static async Task<Results<Ok<OrderDto>, NotFound>> GetOrder(int id, RoasteryDbContext db, CancellationToken ct)
{
var order = await db.Orders.AsNoTracking().Include(o => o.Lines).FirstOrDefaultAsync(o => o.Id == id, ct);
return order is null ? TypedResults.NotFound() : TypedResults.Ok(order.ToDto());
}
// CreateOrder (above), ListOrders (Step 4), ChangeStatus (Step 5)
}
Comment out the ListOrders and ChangeStatus mappings until you write them.
Send the valid POST in module-2.http. It becomes order 3 (the seed made 1 and 2):
HTTP/1.1 201 Created
Location: https://localhost:7181/api/orders/3
Then send the one with quantity 0 (fails annotation validation), the one with product 999 (fails your stock check), and the duplicate-product one (fails IValidatableObject). All three return 400 with the same body shape; only errors differs:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": { "Lines[0].Quantity": ["The field Quantity must be between 1 and 50."] },
"traceId": "00-5c8f9341f068de0255d56c032db9b45b-358cd249afcc79b3-00"
}
Step 4: List orders with paging
Implement GET /api/orders?page=&pageSize=&status= returning PagedResult<OrderSummaryDto>, following the projection pattern on the concepts page. Bind the query string with [AsParameters] OrderQuery, clamp pageSize to 1–100, and treat an unparseable status as "no filter".
static async Task<Ok<PagedResult<OrderSummaryDto>>> ListOrders(
[AsParameters] OrderQuery query, RoasteryDbContext db, CancellationToken ct)
{
var page = Math.Max(1, query.Page);
var pageSize = Math.Clamp(query.PageSize, 1, 100);
OrderStatus? status = Enum.TryParse<OrderStatus>(query.Status, true, out var s) ? s : null;
var orders = db.Orders.AsNoTracking()
.Where(o => status == null || o.Status == status)
.OrderByDescending(o => o.PlacedAt);
var total = await orders.CountAsync(ct);
var items = await orders
.Skip((page - 1) * pageSize).Take(pageSize)
.Select(o => new OrderSummaryDto(o.Id, o.CustomerId, o.Status.ToString(), o.Total, o.PlacedAt))
.ToListAsync(ct);
return TypedResults.Ok(new PagedResult<OrderSummaryDto>(items, page, pageSize, total));
}
Watch the console: the SQL log shows one COUNT and one SELECT … ORDER BY "o"."PlacedAt" DESC LIMIT … OFFSET …, with only the summary columns.
Step 5: Enforce the lifecycle
Add Domain/OrderLifecycle.cs with the transition table and the exception the endpoint throws. The exception keeps From and To so the handler can report them:
using Roastery.Api.Models;
namespace Roastery.Api.Domain;
public static class OrderLifecycle
{
static readonly Dictionary<OrderStatus, OrderStatus[]> Allowed = new()
{
[OrderStatus.Pending] = [OrderStatus.Roasting, OrderStatus.Cancelled],
[OrderStatus.Roasting] = [OrderStatus.Ready],
[OrderStatus.Ready] = [OrderStatus.PickedUp],
};
public static bool CanTransition(OrderStatus from, OrderStatus to) =>
Allowed.TryGetValue(from, out var next) && next.Contains(to);
}
public class InvalidOrderTransitionException(OrderStatus from, OrderStatus to)
: Exception($"An order cannot move from {from} to {to}.")
{
public OrderStatus From { get; } = from;
public OrderStatus To { get; } = to;
}
Implement PUT /api/orders/{id:int}/status that takes { "status": "Roasting" }. It has three ways out besides success: an unknown status string returns a ValidationProblem (a value you can check up front), a missing order returns NotFound, and an illegal move throws InvalidOrderTransitionException (a domain rule, translated centrally).
static async Task<Results<Ok<OrderDto>, NotFound, ValidationProblem>> ChangeStatus(
int id, ChangeOrderStatusRequest request, RoasteryDbContext db, CancellationToken ct)
{
if (!Enum.TryParse<OrderStatus>(request.Status, true, out var target))
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
[nameof(request.Status)] = [$"Unknown status '{request.Status}'."]
});
var order = await db.Orders.Include(o => o.Lines).FirstOrDefaultAsync(o => o.Id == id, ct);
if (order is null) return TypedResults.NotFound();
if (!OrderLifecycle.CanTransition(order.Status, target))
throw new InvalidOrderTransitionException(order.Status, target);
order.Status = target;
await db.SaveChangesAsync(ct);
return TypedResults.Ok(order.ToDto());
}
Now add two exception handlers in Errors/: the DomainExceptionHandler from the concepts page (maps the transition exception to 409 with from/to extensions), and a BadRequestExceptionHandler for binding failures. In Development, Minimal APIs throw BadHttpRequestException when a parameter cannot be bound (RouteHandlerOptions.ThrowOnBadRequest) instead of returning a bare 400; this handler turns it into a ProblemDetails.
using Microsoft.AspNetCore.Diagnostics;
namespace Roastery.Api.Errors;
public class BadRequestExceptionHandler(IProblemDetailsService problemDetails) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken ct)
{
if (exception is not BadHttpRequestException e) return false;
httpContext.Response.StatusCode = e.StatusCode;
return await problemDetails.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = httpContext,
ProblemDetails = new() { Title = "Bad request", Detail = e.Message, Status = e.StatusCode }
});
}
}
DomainExceptionHandler has the same shape and also needs using Roastery.Api.Domain;.
Register both and add the middleware (using Roastery.Api.Errors;). Handlers run in registration order until one returns true:
builder.Services.AddExceptionHandler<BadRequestExceptionHandler>();
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
// … after builder.Build() and the seed block:
app.UseExceptionHandler();
app.UseStatusCodePages();
app.UseHttpsRedirection();
The last two requests in module-2.http both target the order you placed with the valid POST (the request is named newOrder, and the PUT URLs read its id from the response). The first moves it Pending → Roasting (expect 200). The second tries Roasting → PickedUp, which skips Ready (expect 409):
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.10",
"title": "Invalid order transition",
"status": 409,
"detail": "An order cannot move from Roasting to PickedUp.",
"from": "Roasting",
"to": "PickedUp",
"traceId": "00-f0674604f2f884eddb035eb677f13e84-cb0203b1455e008c-00"
}
note Repeating the pair
After one run that order is already Roasting, so the "legal" request returns 409 too. Send "Place a valid order" again to get a fresh Pending order, then repeat the two PUTs. If your client says newOrder is undefined, you have not sent that POST yet in this session.
Also try { "status": "Bogus" } (400 with errors.Status) and PUT /api/orders/999/status (404, still application/problem+json thanks to UseStatusCodePages).
Step 6: Compare the errors
You now have four different failures: a binding error (GET /api/orders?page=abc), an annotation validation error, a hand-built ValidationProblem, and a domain exception. Send all four and confirm every body is application/problem+json with type, title, status, and (where relevant) errors.
note
In Development, a binding failure throws BadHttpRequestException rather than quietly returning a bare 400, so Step 5 registered a small BadRequestExceptionHandler that maps it to the same ProblemDetails shape. That is why even a malformed query string comes back as application/problem+json.
The .http file has two "bad input" requests next to each other. GET /api/orders?page=abc is the binding failure (400). GET /api/orders/abc returns 404, not 400: abc fails the {id:int} route constraint, so no endpoint matches and binding never runs.
Stretch goals
- Add
RowVersiontoOrder, the SQLite trigger from the EF Core docs, and catchDbUpdateConcurrencyExceptionin the status endpoint to return409. Prove it with two overlapping requests. - Add
ETagsupport toGET /api/products/{id}: hash the DTO, return it inETag, and return304whenIf-None-Matchmatches. - Add
DELETE /api/orders/{id}that only succeeds while the order isPendingand restores stock.
Common pitfalls
- Annotations ignored.
AddValidation()is missing. - JSON cycle exception. You returned an entity with navigation properties instead of a DTO.
- "no such table". The migration ran against a different database file than the one the app is using; check the working directory and the connection string.
- "No project was found". You ran
dotnet efoutsidesrc/Roastery.Api. DateTimeOffsetordering not supported. SQLite cannotORDER BYaDateTimeOffset; add thePlacedAtticks conversion, then add a new migration (or deleteMigrations/androastery.db*and recreateInitialCreate).500onPOST /api/products. A product with that name already exists; the name is unique now.409on a transition that should be legal. The order already moved on an earlier run; see the note in Step 5.AddSingletonon aDbContext-backed service. ADbContextis scoped; a singleton that captures it will fail on the second request.
Checkpoint
git add -A && git commit -m "Lab 2 complete"
# or: git checkout checkpoint-2
Next: Module 3: Identity, Tokens, and Authorization