agentleFS
codewithmukeshcodewithmukesh/dotnet-agent-kit/skills/ef-core/SKILL.md

ef-core

Skill853 starsChanged yesterdayMITView on GitHub

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).

7 other projects use a version of this, 1 of them edited.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 1 is distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 6 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use IEntityTypeConfiguration<T> per entity.

    line 29
  2. Distinctive:

    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 …

    line 309

“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

EF Core (.NET 10)

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.

Core Principles

  1. EF Core is the default ORM — Use it unless you have a specific reason not to (extreme perf, legacy DB without FK constraints). See ADR-003.
  2. DbContext is a unit of work — Don't wrap it in another UoW or repository. It already is one.
  3. Reads are projections — .Select() into DTOs. No tracking, no over-fetching, no N+1. If you must return entities from a read, add AsNoTracking().
  4. Writes are tracked entities or bulk ExecuteUpdate/ExecuteDelete — Never load rows just to change one column.
  5. Migrations are code — Review them, test them, never auto-apply in production.

Patterns

DbContext Configuration

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
    }
}

Registration

# 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>()));

Query Projections (Avoid Over-Fetching)

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);
}

Change Tracking on Reads

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);

Single vs Split Queries

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.

Pagination

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);

ExecuteUpdateAsync / ExecuteDeleteAsync

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).

Named Query Filters (EF Core 10)

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.

LeftJoin / RightJoin (.NET 10)

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).

Complex Types (EF Core 10)

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.

Interceptors

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);
    }
}

Compiled Queries

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));
}

Value Converters

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));

Migrations Workflow

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

Anti-patterns

Don't Wrap DbContext in a Repository

// 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.

Don't Use Lazy Loading

// 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);

Don't Filter in Memory

// 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);

Don't Forget to Await

db.SaveChangesAsync();             // BAD — returns before the save completes
await db.SaveChangesAsync(ct);     // GOOD

Don't Track Read-Only Entities

// 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);

Don't Include Several Collections in One Query

// 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);

Don't Page Deep With Skip

// 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);

Don't Reference Outside State in a Query Filter

// 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);

Decision Guide

ScenarioRecommendation
Standard CRUD readProjection to a DTO
Entity read, no editsAsNoTracking(); add identity resolution only with Include
One collection IncludeSingle query
Two or more collection IncludesAsSplitQuery() with a total OrderBy
Feed, infinite scroll, large tableKeyset pagination on an indexed (CreatedAt, Id)
Admin grid with page numbers, small tableOffset Skip/Take + CountAsync
Bulk updates (100+ rows)ExecuteUpdateAsync / ExecuteDeleteAsync
Conditional bulk settersRegular-lambda ExecuteUpdateAsync (EF 10)
Hot-path read queryCompiled query
Left/right join on unmapped keysLeftJoin / RightJoin (.NET 10)
Value object, JSON or table splittingComplex type (not owned)
Complex reporting queryFromSql interpolated, or Dapper
Audit trailsSaveChangesInterceptor
Multi-tenancyNamed query filter on a context member
Soft deletesNamed query filter + SaveChanges override or interceptor
Strongly-typed IDsValue converter
Production migrationIdempotent SQL script, never auto-migrate

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.