software-factory
MAmattpocock/skills336k5,004 new stars in the last 7 days
Entity Framework Core 10: DbContext configuration, named query filters, complex types, LeftJoin/RightJoin, compiled queries, ExecuteUpdateAsync, keyset pagination, and adding EF Core or a provider package. Use for "EF Core", "add EF Core", "Npgsql", "DbContext", "N+1", "AsNoTracking", "named query filter", "LeftJoin", "split query". Do NOT use for adding or applying migrations or upgrading existing packages (use migrate), caching results (use caching), or per-module DbContext layout (use modular-slices).
Targets EF Core 10 (LTS, supported until 2028-11-10). New-in-10 details, SQL output and the EF Core 11 note live in references/ef-core-10.md.
.Select() into DTOs. No tracking, no over-fetching, no N+1. If you must return entities from a read, add AsNoTracking().ExecuteUpdate/ExecuteDelete — Never load rows just to change one column.Use IEntityTypeConfiguration<T> per entity; keep the context thin.
public sealed class AppDbContext(DbContextOptions<AppDbContext> options, ITenantAccessor tenant)
: DbContext(options)
{
// Query filters read this member; EF re-evaluates it for every context instance.
private Guid CurrentTenantId => tenant.TenantId;
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
modelBuilder.Entity<Order>()
.HasQueryFilter("SoftDelete", o => !o.IsDeleted)
.HasQueryFilter("Tenant", o => o.TenantId == CurrentTenantId);
}
}
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Total).HasPrecision(18, 2);
builder.HasMany(o => o.Items).WithOne().HasForeignKey(i => i.OrderId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(o => new { o.CreatedAt, o.Id }); // backs keyset pagination
}
}
# EF Core 11 is now the newest stable; an unversioned add fails on net10.0.
# Look up the newest 10.0.x and pin it exactly (floating "10.*" breaks
# reproducible restores and needs an opt-in under central package management).
dotnet package search Microsoft.EntityFrameworkCore --exact-match
dotnet add package Microsoft.EntityFrameworkCore --version <newest 10.0.x>
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version <newest 10.0.x>
builder.Services.AddDbContext<AppDbContext>((sp, options) => options
.UseNpgsql(builder.Configuration.GetConnectionString("Default"))
.AddInterceptors(sp.GetRequiredService<AuditInterceptor>()));
public async Task<OrderResponse?> GetOrderAsync(Guid id, CancellationToken ct)
{
return await db.Orders
.Where(o => o.Id == id)
.Select(o => new OrderResponse(
o.Id, o.Total, o.CreatedAt,
o.Items.Select(i => new OrderItemResponse(i.ProductName, i.Quantity, i.Price)).ToList()))
.FirstOrDefaultAsync(ct);
}
A projection to a DTO is never tracked, so it needs nothing extra. Only entity results need a tracking decision:
// Read-only entities: skip the change tracker
var orders = await db.Orders.AsNoTracking()
.Where(o => o.CustomerId == customerId)
.ToListAsync(ct);
// Read-only entities with Include: AsNoTracking returns one copy per row;
// identity resolution returns one instance per key, without tracking cost
var withItems = await db.Orders
.AsNoTrackingWithIdentityResolution()
.Include(o => o.Items)
.ToListAsync(ct);
One Include of one collection: single query. Two or more collection Includes (or a collection under a collection) multiply rows (cartesian explosion): use AsSplitQuery().
var orders = await db.Orders
.Include(o => o.Items)
.Include(o => o.Payments)
.AsSplitQuery()
.OrderBy(o => o.CreatedAt).ThenBy(o => o.Id) // total order keeps the split queries consistent
.ToListAsync(ct);
// Or make it the default; opt out per query with AsSingleQuery()
options.UseNpgsql(cs, npgsql => npgsql.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
Why: split queries trade one round trip for N, and the data can change between them. Take that trade only when row multiplication is the bigger cost.
Offset (Skip/Take) is fine for small tables and "jump to page N" UIs. It re-reads every skipped row, so deep pages get slower. For feeds, infinite scroll and APIs, use keyset (seek) pagination:
public sealed record Cursor(DateTimeOffset CreatedAt, Guid Id);
public async Task<(List<OrderSummary> Items, Cursor? Next)> ListAfterAsync(
Cursor? after, int pageSize, CancellationToken ct)
{
var query = db.Orders.AsNoTracking();
if (after is not null)
{
query = query.Where(o => o.CreatedAt < after.CreatedAt
|| (o.CreatedAt == after.CreatedAt && o.Id.CompareTo(after.Id) < 0));
}
var rows = await query
.OrderByDescending(o => o.CreatedAt).ThenByDescending(o => o.Id) // unique tiebreaker
.Take(pageSize + 1) // the extra row says whether another page exists
.Select(o => new { o.Id, o.CreatedAt, o.CustomerName, o.Total, o.Status })
.ToListAsync(ct);
var page = rows.Take(pageSize).ToList();
var next = rows.Count > pageSize ? new Cursor(page[^1].CreatedAt, page[^1].Id) : null;
return (page.Select(r => new OrderSummary(r.Id, r.CustomerName, r.Total, r.Status)).ToList(), next);
}
Why: the WHERE seeks straight to the cursor using the (CreatedAt, Id) index, so page 1000 costs the same as page 1, and inserts between requests don't shift rows. Encode the cursor as opaque base64 in the API. Offset with a total count:
var query = db.Orders
.OrderByDescending(o => o.CreatedAt).ThenByDescending(o => o.Id)
.Select(o => new OrderSummary(o.Id, o.CustomerName, o.Total, o.Status));
var totalCount = await query.CountAsync(ct);
var items = await query.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct);
Bulk operations that bypass change tracking. In EF Core 10 the setter is a regular lambda, so conditional setters are plain if statements.
await db.Orders
.Where(o => o.Status == OrderStatus.Pending && o.CreatedAt < cutoff)
.ExecuteUpdateAsync(s => s
.SetProperty(o => o.Status, OrderStatus.Expired)
.SetProperty(o => o.UpdatedAt, clock.GetUtcNow()),
ct);
await db.Orders
.Where(o => o.Id == id)
.ExecuteUpdateAsync(s =>
{
s.SetProperty(o => o.UpdatedAt, clock.GetUtcNow());
if (newName is not null)
{
s.SetProperty(o => o.CustomerName, newName); // added only when needed
}
}, ct);
await db.Orders
.Where(o => o.Status == OrderStatus.Cancelled && o.CreatedAt < archiveCutoff)
.ExecuteDeleteAsync(ct);
Note: these skip SaveChanges interceptors and tracked entities, so set audit columns yourself (as above).
Several filters per entity, each disabled by name. Setup is in the DbContext sample above.
var all = await db.Orders.IgnoreQueryFilters().ToListAsync(ct); // every filter off
var withDeleted = await db.Orders.IgnoreQueryFilters(["SoftDelete"]).ToListAsync(ct); // tenant filter stays on
Why: a second unnamed HasQueryFilter silently overwrites the first, and one && filter can't be partly disabled. Filters must reference a member of the context (CurrentTenantId), never a static or an outside field, so EF can parameterize per instance. Inside IEntityTypeConfiguration<T> there is no context instance, so define tenant filters in OnModelCreating.
var rows = db.Customers
.LeftJoin(db.Regions, c => c.RegionId, r => r.Id,
(c, r) => new { c.Name, Region = r!.Name ?? "[NONE]" });
Replaces the GroupJoin + SelectMany + DefaultIfEmpty dance. Prefer a navigation property when the relationship is mapped; use LeftJoin for unrelated keys. Method syntax only (no query-syntax form yet).
Value objects with no identity: table splitting by default, one JSON column with ToJson(). Prefer over owned types.
builder.ComplexProperty(o => o.ShippingAddress); // columns in Orders
builder.ComplexProperty(o => o.BillingAddress, b => b.ToJson()); // optional, one JSON column
builder.ComplexProperty(o => o.Location); // a struct works too
Details: optional complex types need one required property; collections need ToJson() and are not supported for structs; JSON complex properties can be bulk-updated with ExecuteUpdateAsync(s => s.SetProperty(o => o.Meta.Views, o => o.Meta.Views + 1)). See the reference.
public sealed class AuditInterceptor(TimeProvider clock) : SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
{
var context = eventData.Context;
if (context is null) return ValueTask.FromResult(result);
var now = clock.GetUtcNow();
foreach (var entry in context.ChangeTracker.Entries<IAuditable>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedAt = now;
entry.Entity.UpdatedAt = now;
break;
case EntityState.Modified:
entry.Entity.UpdatedAt = now;
break;
}
}
return ValueTask.FromResult(result);
}
}
Hot-path queries with a fixed shape.
public static class OrderQueries
{
public static readonly Func<AppDbContext, Guid, CancellationToken, Task<Order?>> GetById =
EF.CompileAsyncQuery((AppDbContext db, Guid id, CancellationToken ct) =>
db.Orders.Include(o => o.Items).FirstOrDefault(o => o.Id == id));
}
builder.Property(o => o.Status).HasConversion<string>().HasMaxLength(50); // enum as string
public readonly record struct OrderId(Guid Value);
builder.Property(o => o.Id).HasConversion(id => id.Value, value => new OrderId(value));
dotnet ef migrations add AddOrderIndex --project src/MyApp.Infrastructure --startup-project src/MyApp.Api
# ALWAYS review the generated migration: data loss, index strategy, constraint names
# Production: idempotent SQL script, never auto-migrate
dotnet ef migrations script --idempotent --output migrations.sql
// BAD — hides IQueryable, Include, projections and bulk APIs
public interface IOrderRepository { Task<Order?> GetByIdAsync(Guid id); Task AddAsync(Order order); }
// GOOD — inject the DbContext
public sealed class GetOrderHandler(AppDbContext db)
{
public async Task<Order?> Handle(Guid id, CancellationToken ct) => await db.Orders.FindAsync([id], ct);
}
When someone asks for a generic repository or unit of work, answer with the GOOD version and the reasons, then ask whether they still want the wrapper. Don't write it in the same reply: a wrapper built "as requested" gets copied everywhere.
// BAD — hidden N+1 queries
options.UseLazyLoadingProxies();
// GOOD — explicit Include or projection
var orders = await db.Orders.Include(o => o.Items).Where(o => o.CustomerId == customerId).ToListAsync(ct);
// BAD — loads ALL orders, filters in C#
var pending = (await db.Orders.ToListAsync(ct)).Where(o => o.Status == OrderStatus.Pending);
// GOOD — filter in the database
var pending = await db.Orders.Where(o => o.Status == OrderStatus.Pending).ToListAsync(ct);
db.SaveChangesAsync(); // BAD — returns before the save completes
await db.SaveChangesAsync(ct); // GOOD
// BAD — change tracker snapshots every row for a read
var orders = await db.Orders.Where(o => o.CustomerId == customerId).ToListAsync(ct);
// GOOD — project, or at least AsNoTracking
var orders = await db.Orders.AsNoTracking().Where(o => o.CustomerId == customerId).ToListAsync(ct);
// BAD — Items x Payments rows per order (cartesian explosion)
var orders = await db.Orders.Include(o => o.Items).Include(o => o.Payments).ToListAsync(ct);
// GOOD
var orders = await db.Orders.Include(o => o.Items).Include(o => o.Payments)
.AsSplitQuery().ToListAsync(ct);
// BAD — database reads and discards 500,000 rows
var page = await db.Orders.OrderBy(o => o.CreatedAt).Skip(500_000).Take(50).ToListAsync(ct);
// GOOD — keyset: seek past the last row seen (see Pagination)
var page = await db.Orders.Where(o => o.CreatedAt > last).OrderBy(o => o.CreatedAt).Take(50).ToListAsync(ct);
// BAD — static/field value is baked into the cached model; every tenant sees the first tenant's data
modelBuilder.Entity<Order>().HasQueryFilter(o => o.TenantId == TenantHolder.Current);
// GOOD — a member of the DbContext (primary-constructor accessor), see DbContext Configuration
modelBuilder.Entity<Order>().HasQueryFilter("Tenant", o => o.TenantId == CurrentTenantId);
| Scenario | Recommendation |
|---|---|
| Standard CRUD read | Projection to a DTO |
| Entity read, no edits | AsNoTracking(); add identity resolution only with Include |
One collection Include | Single query |
Two or more collection Includes | AsSplitQuery() with a total OrderBy |
| Feed, infinite scroll, large table | Keyset pagination on an indexed (CreatedAt, Id) |
| Admin grid with page numbers, small table | Offset Skip/Take + CountAsync |
| Bulk updates (100+ rows) | ExecuteUpdateAsync / ExecuteDeleteAsync |
| Conditional bulk setters | Regular-lambda ExecuteUpdateAsync (EF 10) |
| Hot-path read query | Compiled query |
| Left/right join on unmapped keys | LeftJoin / RightJoin (.NET 10) |
| Value object, JSON or table splitting | Complex type (not owned) |
| Complex reporting query | FromSql interpolated, or Dapper |
| Audit trails | SaveChangesInterceptor |
| Multi-tenancy | Named query filter on a context member |
| Soft deletes | Named query filter + SaveChanges override or interceptor |
| Strongly-typed IDs | Value converter |
| Production migration | Idempotent SQL script, never auto-migrate |
MAmattpocock/skills336k5,004 new stars in the last 7 days
MAmattpocock/skills336k5,004 new stars in the last 7 days
AFaffaan-m/ECC314k4,125 new stars in the last 7 days
AFaffaan-m/ECC314k4,125 new stars in the last 7 days
AFaffaan-m/ECC314k4,125 new stars in the last 7 days
DIDietrichGebert/ponytail202k4,780 new stars in the last 7 days