SkillPilotAI

Project: plan, API and EF Core

This is part one of the capstone: an Order management API built with Minimal APIs and EF Core on SQLite. It goes from requirements and folder structure to entities, migrations and CRUD, and fixes a first draft where the client could set its own total.

73.1 Requirements

  • Products: full CRUD.
  • Orders: place, list and cancel.
  • Price and total are calculated only on the server.
  • No order can go beyond the available stock.
  • Errors are returned as Problem Details (application/problem+json).
  • Auth, tests and Docker come in the next video.

73.2 Solution and packages

  • dotnet new sln creates a .slnx solution; the webapi project goes under src/.
  • Add the SQLite provider and Microsoft.EntityFrameworkCore.Design.
  • dotnet-ef is installed as a local tool (tool manifest) so everyone uses the same version.
Terminal
dotnet new sln -n OrderApidotnet new webapi -n OrderApi -o src/OrderApidotnet sln add src/OrderApi cd src/OrderApidotnet add package \  Microsoft.EntityFrameworkCore.Sqlitedotnet add package \  Microsoft.EntityFrameworkCore.Design cd ../..dotnet new tool-manifestdotnet tool install dotnet-ef
Output
$ dotnet new sln -n OrderApiThe template "Solution File" was created successfully.$ dotnet sln add src/OrderApiProject `src\OrderApi\OrderApi.csproj` added to the solution. $ dotnet tool install dotnet-efTool 'dotnet-ef' (version '10.0.14') was successfully installed.

73.3 Folder structure

  • The Clean Architecture layers appear as folders, not separate projects.
  • Entities = domain, Data = infrastructure (DbContext, migrations, conflict handler).
  • Features/<Name> keeps each feature's endpoints, DTOs and service together (vertical slices).
Output
OrderApi.slnxdotnet-tools.jsonsrc/OrderApi/  Program.cs  Entities/    Product.cs, Order.cs  Data/    AppDbContext.cs, DbConflictHandler.cs    Migrations/  Features/    Products/  endpoints + DTOs    Orders/    endpoints + DTOs + OrderServicetests/       (next video)

73.4 Entities and DbContext

  • Product: Id, Name, Price, Stock. Order uses the OrderStatus enum.
  • CreatedAt is a DateTimeOffset (keeps UTC); money (Total) is decimal.
  • OrderItem stores UnitPrice, so an old bill stays the same if the price changes tomorrow.
  • Fluent API: unique Name, Stock as a concurrency token, Status stored as string, DeleteBehavior.Restrict so a product in an order cannot be deleted.
C#
public enum OrderStatus{    Placed, Shipped, Cancelled} public class Order{    public int Id { get; set; }    public required string Email { get; set; }    public OrderStatus Status { get; set; }    public DateTimeOffset CreatedAt { get; set; }    public decimal Total { get; set; }    public List<OrderItem> Items { get; set; } = [];}
C#
b.Entity<Product>(p =>{    p.HasIndex(x => x.Name).IsUnique();    p.Property(x => x.Stock)        .IsConcurrencyToken();});b.Entity<Order>()    .Property(o => o.Status)    .HasConversion<string>();b.Entity<OrderItem>()    .HasOne(i => i.Product)    .WithMany()    .OnDelete(DeleteBehavior.Restrict);

73.5 Program.cs: services

RegistrationWhy
AddDbContext + UseSqliteEF Core with the Orders connection string
AddScoped<OrderService>One service per request, same lifetime as the DbContext
AddSingleton(TimeProvider.System)Tests can plug in a fake clock
AddValidationBuilt-in validation of DTO attributes (400 before the handler runs)
AddProblemDetails + DbConflictHandlerErrors as Problem Details; a DB conflict becomes 409
JsonStringEnumConverterEnums go out as text ("Placed") in JSON
C#
builder.Services.AddDbContext<AppDbContext>(o =>    o.UseSqlite(builder.Configuration        .GetConnectionString("Orders")));builder.Services.AddScoped<OrderService>();builder.Services.AddSingleton(    TimeProvider.System); builder.Services.AddValidation();builder.Services.AddProblemDetails();builder.Services    .AddExceptionHandler<DbConflictHandler>();builder.Services.ConfigureHttpJsonOptions(o =>    o.SerializerOptions.Converters        .Add(new JsonStringEnumConverter()));

73.6 Database via migrations

  • Use migrations, not EnsureCreated: a migration is C# code committed to Git.
  • migrations add creates InitialCreate; database update applies it and creates the tables and the unique index.
Terminal
dotnet ef migrations add InitialCreate \  --project src/OrderApi \  --output-dir Data/Migrations dotnet ef database update \  --project src/OrderApi
Output
$ dotnet ef migrations add InitialCreate \  --project src/OrderApi --output-dir Data/MigrationsBuild started...Build succeeded.Done. To undo this action, use 'ef migrations remove' $ dotnet ef database update --project src/OrderApiApplying migration '20261106223940_InitialCreate'.      CREATE TABLE "Orders" (...);      CREATE TABLE "Products" (...);      CREATE TABLE "OrderItems" (...);      CREATE UNIQUE INDEX "IX_Products_Name"      ON "Products" ("Name");Done.

73.7 Products: Minimal API CRUD

  • MapGroup("/api/products") gives a common prefix and tag; handlers return TypedResults.
  • Create -> 201 Created with Location; invalid body -> 400 with field errors; duplicate name -> 409 Conflict.
C#
public static void MapProductEndpoints(    this IEndpointRouteBuilder app){    var g = app.MapGroup("/api/products")        .WithTags("Products");    g.MapGet("/", GetAll);    g.MapGet("/{id:int}", GetById);    g.MapPost("/", Create);    g.MapPut("/{id:int}", Update);    g.MapDelete("/{id:int}", Delete);}
Output
$ curl -i localhost:5073/api/products \  -H "Content-Type: application/json" \  -d '{"name":"Mixer Grinder","price":2499,"stock":5}'HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: /api/products/1{"id":1,"name":"Mixer Grinder","price":2499,"stock":5} $ curl -i localhost:5073/api/products \  -H "Content-Type: application/json" \  -d '{"name":"","price":0,"stock":-1}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json"errors": {  "Name": ["The Name field is required."],  "Price": ["The field Price must be between 1 and 500000."],  "Stock": ["The field Stock must be between 0 and 10000."]} $ curl -i localhost:5073/api/products \  -H "Content-Type: application/json" \  -d '{"name":"Steel Bottle","price":450,"stock":3}'HTTP/1.1 409 ConflictContent-Type: application/problem+json{ "title": "Duplicate or conflicting data.", "status": 409 }
RequestStatusWhy
Valid new product201 CreatedSaved, Location header points to it
Empty name, price 0, stock -1400 Bad RequestValidation attributes fail
Name that already exists409 ConflictUnique index; DbConflictHandler maps it

73.8 The bug: entity straight from the body

  • The first draft binds the Order entity directly from the request body and saves it.
  • The client sent total 1, status Shipped and unitPrice 0.5 for two Mixer Grinders: 201 Created.
  • CreatedAt is year 0001 and the stock is still 5: nothing was checked.
C#
app.MapPost("/api/orders",    async (Order order, AppDbContext db) =>{    db.Orders.Add(order);    await db.SaveChangesAsync();    return TypedResults.Created(        $"/api/orders/{order.Id}", order);});
Output
$ curl -i localhost:5073/api/orders \  -H "Content-Type: application/json" \  -d '{"email":"amit@example.com","status":"Shipped",       "total":1,"items":[{"productId":1,       "quantity":2,"unitPrice":0.5}]}'HTTP/1.1 201 CreatedLocation: /api/orders/1{ "id": 1, "email": "amit@example.com",  "status": "Shipped",  "createdAt": "0001-01-01T00:00:00+00:00",  "total": 1,  "items": [{ "id": 1, "orderId": 1, "productId": 1,    "product": null, "quantity": 2, "unitPrice": 0.5 }] } $ curl -i localhost:5073/api/products/1HTTP/1.1 200 OK{"id":1,"name":"Mixer Grinder","price":2499.0,"stock":5}
What went wrong?
  1. 1.Order entity binds from the body

  2. 2.Client controls every field: total, status, unitPrice

  3. 3.No stock check, no server price

  4. 4.Saved as-is -> 201 Created with total 1

  5. 5.Fix: request DTO + validation + OrderService

Never bind or return an entity

73.9 Fix 1: request DTO + validation

  • CreateOrderRequest has only Email and Items, so there is no way to send a total or status.
  • Email must be valid; Items needs 1 to 20 lines; Quantity is 1 to 10.
  • AddValidation checks nested lists too (Items[0].Quantity) and returns 400 before the endpoint runs.
C#
public record CreateOrderRequest(    [Required, EmailAddress] string Email,    [Required, MinLength(1), MaxLength(20)]    List<OrderLine> Items); public record OrderLine(    [Range(1, int.MaxValue)] int ProductId,    [Range(1, 10)] int Quantity);
Output
$ curl -i localhost:5073/api/orders \  -H "Content-Type: application/json" \  -d '{"email":"not-an-email","items":[]}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json"errors": {  "Email": ["The Email field is not a valid e-mail address."],  "Items": ["The field Items must be a string or array type             with a minimum length of '1'."]} $ curl -i localhost:5073/api/orders \  -H "Content-Type: application/json" \  -d '{"email":"ravi@example.com",       "items":[{"productId":2,"quantity":0}]}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json"errors": {  "Items[0].Quantity": ["The field Quantity must be between 1 and 10."]}

73.10 Fix 2: OrderService, stock check in one query

  • Business rules live in OrderService; the endpoint stays thin.
  • All products load in one query (WHERE Id IN).
  • CheckStock verifies each product exists and has enough stock; errors become a ValidationProblem (400).
C#
public async Task<PlaceResult> PlaceAsync(    CreateOrderRequest req){    var ids = req.Items.Select(i => i.ProductId);    var products = await db.Products        .Where(p => ids.Contains(p.Id))        .ToDictionaryAsync(p => p.Id);     var errors = CheckStock(req, products);    if (errors.Count > 0)        return new(null, errors);
Output
# dotnet run log (EF Core SQL)info: Microsoft.EntityFrameworkCore.Database.Command[20101]      SELECT "p"."Id", "p"."Name", "p"."Price", "p"."Stock"      FROM "Products" AS "p"      WHERE "p"."Id" IN (@ids1, @ids2) $ curl -i localhost:5073/api/orders \  -H "Content-Type: application/json" \  -d '{"email":"ravi@example.com","items":[       {"productId":2,"quantity":3},       {"productId":42,"quantity":1}]}'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json"errors": {  "Items[0]": ["Only 1 left of Steel Bottle 1L."],  "Items[1]": ["Product not found."]}

73.11 Fix 3: price from the server

  • The order gets status Placed and time from TimeProvider.
  • Stock is reduced and the total uses the database price, not the client's.
  • One SaveChangesAsync writes everything in one transaction.
  • The UPDATE has the old Stock in its WHERE: the concurrency token at work.
C#
foreach (var line in req.Items){    var product = products[line.ProductId];    product.Stock -= line.Quantity;    order.Total += product.Price * line.Quantity;    order.Items.Add(new OrderItem    {        ProductId = product.Id,        Quantity = line.Quantity,        UnitPrice = product.Price    });}db.Orders.Add(order);await db.SaveChangesAsync();return new(order, []);
Output
$ curl -i localhost:5073/api/orders \  -H "Content-Type: application/json" \  -d '{"email":"amit@example.com","items":[       {"productId":1,"quantity":2},       {"productId":2,"quantity":1}]}'HTTP/1.1 201 CreatedLocation: /api/orders/1{ "id": 1, "email": "amit@example.com",  "status": "Placed",  "createdAt": "2026-11-06T22:51:30.9850642+00:00",  "total": 5447.0,  "items": [    { "productId": 1, "quantity": 2, "unitPrice": 2499.0 },    { "productId": 2, "quantity": 1, "unitPrice": 449.0 } ] } # dotnet run log (EF Core SQL)info: Microsoft.EntityFrameworkCore.Database.Command[20101]      UPDATE "Products" SET "Stock" = @p0      WHERE "Id" = @p1 AND "Stock" = @p2      RETURNING 1;
How an order is placed
  1. 1.Validation: DTO attributes -> 400 if invalid

  2. 2.Stock check: one query, WHERE Id IN

  3. 3.Server price: items + total from the DB

  4. 4.SaveChanges: one transaction -> 201 Created

The client says what it wants, the server decides the price

73.12 Checkpoint: cancel twice

  • CancelAsync returns null (missing), false (not Placed) or true (cancelled).
  • Results<NoContent, NotFound, ProblemHttpResult> maps them to 404 / 409 / 204.
  • Second cancel of order 1 -> 409 Conflict, because only a Placed order can be cancelled.
C#
static async Task<Results<NoContent, NotFound,    ProblemHttpResult>> Cancel(    int id, OrderService orders) =>    await orders.CancelAsync(id) switch    {        null => TypedResults.NotFound(),        false => TypedResults.Problem(            "Only placed orders can be cancelled.",            statusCode: 409),        true => TypedResults.NoContent()    };
Output
$ curl -i -X POST localhost:5073/api/orders/1/cancelHTTP/1.1 204 No Content $ curl -i -X POST localhost:5073/api/orders/1/cancelHTTP/1.1 409 ConflictContent-Type: application/problem+json{ "title": "Conflict", "status": 409,  "detail": "Only placed orders can be cancelled." }

73.13 Common mistake: a query in a loop (N+1)

C#
// Wrong: 3 items = 3 SELECTs (N+1)var products = new Dictionary<int, Product>();foreach (var line in req.Items){    var p = await db.Products        .FirstOrDefaultAsync(            x => x.Id == line.ProductId);    if (p is not null) products[p.Id] = p;}
C#
// Right: One query: WHERE Id IN (...)var ids = req.Items.Select(i => i.ProductId);var products = await db.Products    .Where(p => ids.Contains(p.Id))    .ToDictionaryAsync(p => p.Id);
  • A FirstOrDefaultAsync inside the loop sends one SELECT per line: 3 items = 3 queries.
  • Contains builds a single WHERE Id IN (...) query for 1 or 20 items.

73.14 Misconception and rules

  • Clean Architecture does not require 4 projects; here the same layers are folders.
  • Split into projects when the project grows; add a Repository only when the DbContext alone is not enough.
  1. DTOs, never entities, in requests and responses.
  2. Price, total and status are decided by the server.
  3. Validation in attributes, business rules in a service.
  4. Change the schema only through migrations.
  5. Load related data in one query and put a concurrency token on shared stock.

73.15 Interview tips

  • Describe it: Order management API with Minimal APIs + EF Core on SQLite; products CRUD, orders place/list/cancel.
  • Stress that the client sends only product id and quantity; price, total and stock check happen on the server in one transaction.
  • Mention validation via attributes, errors as Problem Details, and a concurrency token on Stock.
  • Show you know N+1 and how Contains -> WHERE IN avoids it.