Community编程与开发github.com

Entity Framework Core 最佳实践模式

Entity Framework Core 最佳实践,包括默认无追踪、导航集合查询拆分、迁移管理、专用迁移服务以及需避免的常见陷阱。

Entity Framework Core 最佳实践模式 是什么?

此技能是一套关于 Entity Framework Core 的全面最佳实践指南,专为使用 EF Core 的 .NET 开发者设计。它涵盖了五个核心模式:默认使用无追踪查询以优化只读性能、禁止手动编辑迁移文件、通过专用迁移服务在 .NET Aspire 中管理数据库变更、使用执行策略处理瞬态故障,以及使用 ExecuteUpdate/ExecuteDelete 进行批量操作以提高效率。此外,还详细解释了常见陷阱,如 N+1 查询问题、无追踪模式下的更新遗漏、追踪冲突以及不一致的异步操作。该技能支持所有使用 EF Core 的项目,特别适用于通过 .NET Aspire 编排的新项目。它提供了清晰的代码示例、结构化项目布局和实用命令,帮助开发者编写更高效、更可维护的数据库访问代码。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/efcore-patterns

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Entity Framework Core 模式

何时使用此技能

在以下情况下使用此技能:

  • 在新项目中设置 EF Core
  • 优化查询性能
  • 管理数据库迁移
  • 将 EF Core 与 .NET Aspire 集成
  • 调试更改追踪问题
  • 高效加载多个导航集合(查询拆分)

核心原则

  1. 默认无追踪 (NoTracking) - 大多数查询是只读的;选择加入追踪
  2. 绝不手动编辑迁移 - 始终使用 CLI 命令
  3. 专用迁移服务 - 将迁移执行与应用程序启动分离
  4. 重试执行策略 - 处理瞬态数据库故障
  5. 显式更新 - 使用 NoTracking 时,显式标记实体进行更新

模式 1:默认无追踪

配置您的 DbContext 以默认禁用更改追踪。这可以提高读取密集型工作负载的性能。

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
        // 默认禁用更改追踪以提高只读查询性能
        // 对于需要追踪更改的查询,请显式使用 .AsTracking()
        ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    }

    public DbSet<Order> Orders => Set<Order>();
    public DbSet<Customer> Customers => Set<Customer>();
}

当无追踪生效时

只读查询正常工作:

// ✅ 快速读取 - 无追踪开销
var orders = await dbContext.Orders
    .Where(o => o.Status == OrderStatus.Pending)
    .ToListAsync();

写入需要显式处理:

// ❌ 错误 - 实体未被追踪,SaveChanges 不做任何事
var order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);
order.Status = OrderStatus.Shipped;
await dbContext.SaveChangesAsync(); // 什么都没发生!

// ✅ 正确 - 显式标记实体进行更新
var order = await dbContext.Orders.FirstOrDefaultAsync(o => o.Id == orderId);
order.Status = OrderStatus.Shipped;
dbContext.Orders.Update(order); // 将整个实体标记为已修改
await dbContext.SaveChangesAsync();

// ✅ 同样正确 - 对查询使用 AsTracking()
var order = await dbContext.Orders
    .AsTracking()
    .FirstOrDefaultAsync(o => o.Id == orderId);
order.Status = OrderStatus.Shipped;
await dbContext.SaveChangesAsync(); // 生效!

何时使用追踪

场景使用追踪?原因
在 UI 中显示数据否只读,无更新
API GET 端点否返回数据,无变更
更新单个实体是 或 显式 Update()需要保存更改
带导航属性的复杂更新是追踪处理关系
批量操作否 + ExecuteUpdate更高效

显式添加/更新模式

public class OrderService
{
    private readonly ApplicationDbContext _db;

    // 创建 - 始终使用 Add(无论是否追踪都有效)
    public async Task<Order> CreateOrderAsync(Order order)
    {
        _db.Orders.Add(order);
        await _db.SaveChangesAsync();
        return order;
    }

    // 更新 - 显式标记为已修改
    public async Task UpdateOrderStatusAsync(Guid orderId, OrderStatus newStatus)
    {
        var order = await _db.Orders.FirstOrDefaultAsync(o => o.Id == orderId)
            ?? throw new NotFoundException($"Order {orderId} not found");

        order.Status = newStatus;
        order.UpdatedAt = DateTimeOffset.UtcNow;

        // 由于 DbContext 默认使用 NoTracking,显式标记为已修改
        _db.Orders.Update(order);
        await _db.SaveChangesAsync();
    }

    // 删除 - 附加并移除
    public async Task DeleteOrderAsync(Guid orderId)
    {
        var order = new Order { Id = orderId };
        _db.Orders.Remove(order);
        await _db.SaveChangesAsync();
    }
}

模式 2:绝不手动编辑迁移

关键: 始终使用 EF Core CLI 命令来管理迁移。切勿:

  • 手动编辑迁移文件(除了在 Up()/Down() 中添加自定义 SQL)
  • 直接删除迁移文件
  • 重命名迁移文件
  • 在项目之间复制迁移

创建迁移

# 创建新迁移
dotnet ef migrations add AddCustomerTable \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# 针对特定 DbContext(如果有多个)
dotnet ef migrations add AddCustomerTable \
    --context ApplicationDbContext \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

移除迁移

# 移除最后一个迁移(如果尚未应用)
dotnet ef migrations remove \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# 绝对不要这样做:
# rm Migrations/20240101_AddCustomerTable.cs  # ❌ 坏的做法!

应用迁移

# 应用所有待处理的迁移
dotnet ef database update \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# 应用直到特定迁移
dotnet ef database update AddCustomerTable \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

# 回滚到之前的迁移
dotnet ef database update PreviousMigrationName \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

生成 SQL 脚本

# 为所有迁移生成 SQL 脚本
dotnet ef migrations script \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api \
    --output migrations.sql

# 生成幂等脚本(可安全多次运行)
dotnet ef migrations script \
    --idempotent \
    --project src/MyApp.Infrastructure \
    --startup-project src/MyApp.Api

模式 3:使用 Aspire 的专用迁移服务

使用专用迁移服务将迁移执行与主应用程序分离。这确保了:

  • 迁移在应用程序启动前完成
  • 清晰的关注点分离
  • 在测试环境中可控的种子数据

项目结构

src/
├── MyApp.AppHost/           # Aspire 编排
├── MyApp.Api/               # 主应用程序
├── MyApp.Infrastructure/    # DbContext 和迁移
└── MyApp.MigrationService/  # 专用迁移运行器

MigrationService Program.cs

using MyApp.Infrastructure.Data;
using MyApp.MigrationService;
using Microsoft.EntityFrameworkCore;

var builder = Host.CreateApplicationBuilder(args);

// 添加 Aspire 服务默认值
builder.AddServiceDefaults();

// 添加 PostgreSQL DbContext
var connectionString = builder.Configuration.GetConnectionString("appdb")
    ?? throw new InvalidOperationException("Connection string 'appdb' not found.");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(connectionString, npgsqlOptions =>
        npgsqlOptions.MigrationsAssembly("MyApp.Infrastructure")));

// 添加迁移工作器
builder.Services.AddHostedService<MigrationWorker>();

var host = builder.Build();
host.Run();

MigrationWorker.cs

public class MigrationWorker : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;
    private readonly IHostApplicationLifetime _hostApplicationLifetime;
    private readonly ILogger<MigrationWorker> _logger;

    public MigrationWorker(
        IServiceProvider serviceProvider,
        IHostApplicationLifetime hostApplicationLifetime,
        ILogger<MigrationWorker> logger)
    {
        _serviceProvider = serviceProvider;
        _hostApplicationLifetime = hostApplicationLifetime;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Migration service starting...");

        try
        {
            using var scope = _serviceProvider.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

            await RunMigrationsAsync(dbContext, stoppingToken);

            _logger.LogInformation("Migration service completed successfully.");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Migration service failed: {Error}", ex.Message);
            throw;
        }
        finally
        {
            // 迁移完成后停止应用程序
            _hostApplicationLifetime.StopApplication();
        }
    }

    private async Task RunMigrationsAsync(ApplicationDbContext dbContext, CancellationToken ct)
    {
        // 使用执行策略处理瞬态故障
        var strategy = dbContext.Database.CreateExecutionStrategy();

        await strategy.ExecuteAsync(async () =>
        {
            var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync(ct);

            if (pendingMigrations.Any())
            {
                _logger.LogInformation("Applying {Count} pending migrations...",
                    pendingMigrations.Count());

                await dbContext.Database.MigrateAsync(ct);

                _logger.LogInformation("Migrations applied successfully.");
            }
            else
            {
                _logger.LogInformation("No pending migrations. Database is up to date.");
            }
        });
    }
}

AppHost 配置

var builder = DistributedApplication.CreateBuilder(args);

var postgres = builder.AddPostgres("postgres");
var db = postgres.AddDatabase("appdb");

// 迁移先运行,然后退出
var migrations = builder.AddProject<Projects.MyApp_MigrationService>("migrations")
    .WaitFor(db)
    .WithReference(db);

// API 等待迁移完成
var api = builder.AddProject<Projects.MyApp_Api>("api")
    .WaitForCompletion(migrations)  // 关键:等待迁移完成
    .WithReference(db);

模式 4:用于瞬态故障的执行策略

始终对可能瞬态失败的操作使用 CreateExecutionStrategy():

public async Task UpdateWithRetryAsync(Guid id, Action<Order> update)
{
    var strategy = _dbContext.Database.CreateExecutionStrategy();

    await strategy.ExecuteAsync(async () =>
    {
        var order = await _dbContext.Orders
            .AsTracking()
            .FirstOrDefaultAsync(o => o.Id == id);

        if (order is null) return;

        update(order);
        await _dbContext.SaveChangesAsync();
    });
}

重要提示: 不能将 CreateExecutionStrategy() 与用户发起的事务一起使用。如果需要在重试时使用事务:

var strategy = _dbContext.Database.CreateExecutionStrategy();

await strategy.ExecuteAsync(async () =>
{
    // 事务必须在策略回调内部
    await using var transaction = await _dbContext.Database.BeginTransactionAsync();

    try
    {
        // ... 您的操作 ...
        await _dbContext.SaveChangesAsync();
        await transaction.CommitAsync();
    }
    catch
    {
        await transaction.RollbackAsync();
        throw;
    }
});

模式 5:使用 ExecuteUpdate/ExecuteDelete 进行批量操作

对于批量操作,使用 EF Core 7+ 的 ExecuteUpdateAsync 和 ExecuteDeleteAsync,而不是加载实体:

// ❌ 慢 - 将所有实体加载到内存中
var expiredOrders = await _db.Orders
    .Where(o => o.ExpiresAt < DateTimeOffset.UtcNow)
    .ToListAsync();

foreach (var order in expiredOrders)
{
    order.Status = OrderStatus.Expired;
}
await _db.SaveChangesAsync();

// ✅ 快 - 单个 SQL UPDATE 语句
await _db.Orders
    .Where(o => o.ExpiresAt < DateTimeOffset.UtcNow)
    .ExecuteUpdateAsync(setters => setters
        .SetProperty(o => o.Status, OrderStatus.Expired)
        .SetProperty(o => o.UpdatedAt, DateTimeOffset.UtcNow));

// ✅ 快 - 单个 SQL DELETE 语句
await _db.Orders
    .Where(o => o.Status == OrderStatus.Cancelled && o.CreatedAt < cutoffDate)
    .ExecuteDeleteAsync();

常见陷阱

1. 使用 NoTracking 时忘记更新

// ❌ 静默失败 - 实体未被追踪
var customer = await _db.Customers.FindAsync(id);
customer.Name = "New Name";
await _db.SaveChangesAsync(); // 什么都不做!

// ✅ 显式更新
var customer = await _db.Customers.FindAsync(id);
customer.Name = "New Name";
_db.Customers.Update(customer);
await _db.SaveChangesAsync();

2. N+1 查询问题

// ❌ N+1 查询 - 每个订单一个查询
var customers = await _db.Customers.ToListAsync();
foreach (var customer in customers)
{
    var orders = customer.Orders; // 延迟加载触发查询
}

// ✅ 预先加载 - 单个查询
var customers = await _db.Customers
    .Include(c => c.Orders)
    .ToListAsync();

3. 多个 DbContext 实例的追踪冲突

// ❌ 追踪冲突 - 实体被不同上下文追踪
var order1 = await _db1.Orders.AsTracking().FindAsync(id);
var order2 = await _db2.Orders.AsTracking().FindAsync(id);
order2.Status = OrderStatus.Shipped;
await _db2.SaveChangesAsync(); // 可能抛出异常或行为异常

// ✅ 使用单一上下文或先分离
_db1.Entry(order1).State = EntityState.Detached;

4. 未一致使用 Async

// ❌ 在异步上下文中阻塞调用
var orders = _db.Orders.ToList(); // 阻塞线程

// ✅ 全程使用异步
var orders = await _db.Orders.ToListAsync();

5. 在循环内查询

// ❌ 每次迭代都查询
foreach (var orderId in orderIds)
{
    var order = await _db.Orders.FindAsync(orderId);
    // 处理订单
}

// ✅ 单个查询
var orders = await _db.Orders
    .Where(o => orderIds.Contains(o.Id))
    .ToListAsync();

DI 中的 DbContext 生命周期

ASP.NET Core(默认作用域)

// Scoped = 每个 HTTP 请求一个实例
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseNpgsql(connectionString));

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相关技能