Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

ef-core

БесплатноБез исполняемых скриптовНе проверен

Entity Framework Core 10: DbContext configuration, named query filters, complex types, LeftJoin/RightJoin, compiled queries, ExecuteUpdateAsync, keyset…

codewithmukeshот codewithmukesh★ 858 звёзд на GitHub

Об этом скилле

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 nul
Полный SKILL.md на GitHub

Установить ef-core в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/ef-core-10.md

FAQ

Что делает скилл ef-core?

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

Как установить скилл ef-core?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл ef-core запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить ef-core с