Part 7 · 1 chapters · ~8 min

ASP.NET Core and EF Core Internals

Kestrel and its I/O pipelines, the middleware pipeline as delegates, endpoint routing, model binding and source-generated JSON, DI container internals and lifetimes, EF Core: DbContext, change tracking, expression-tree translation, migrations, concurrency tokens, N+1 and Include, split queries, compiled queries, and when to use Dapper or raw SQL.

8

What the frameworks do for you

code
// middleware is a chain of delegates: each can act before and after the next
app.Use(async (ctx, next) => { var sw = Stopwatch.StartNew(); await next(ctx); log.LogInformation("{Path} {Ms}", ctx.Request.Path, sw.ElapsedMilliseconds); });

// EF Core: see the SQL, avoid N+1, lock money rows explicitly
var q = db.Transfers.Where(t => t.AccountId == id).Include(t => t.Postings);
Console.WriteLine(q.ToQueryString());
var acct = await db.Accounts.FromSql($"SELECT * FROM accounts WHERE id = {id} FOR UPDATE").SingleAsync(ct);

// optimistic concurrency with Postgres xmin
modelBuilder.Entity<Account>().Property<uint>("xmin").IsRowVersion();
try { await db.SaveChangesAsync(ct); } catch (DbUpdateConcurrencyException) { /* reload and retry or fail */ }

dotnet ef migrations add AddHolds && dotnet ef database update     // migrations; review the SQL (Deploy course)
EF CORE: FROM LINQ TO SQL AND BACK
change tracking and SaveChanges
your codeDbContextPostgresdb.Accounts.Where(a => a.Id == id).SingleAsync()SELECT … WHERE id = @p0 LIMIT 2
swipe the figure sideways, or tap expand for full screen
1/4
LINQ to SQL
EF Core translates LINQ expression trees into SQL for the provider (Npgsql); inspect it with ToQueryString() or logging.
expression trees → SQLToQueryString()