Community程式設計與開發github.com

efcore-patterns

Entity Framework Core 最佳實務,包括預設不追蹤 (NoTracking)、導覽集合的查詢分割、移轉管理、專用移轉服務,以及常見陷阱。

efcore-patterns 是什麼?

此技能提供 Entity Framework Core 的完整最佳實務指南,重點在於提升查詢效能、簡化移轉管理,並避免常見錯誤。它涵蓋五大核心模式:預設不追蹤 (NoTracking) 以優化唯讀工作負載;絕不手動編輯移轉檔案,強制使用 CLI 命令管理;透過專用的移轉服務與 .NET Aspire 整合,確保資料庫在應用程式啟動前完成更新;使用 ExecutionStrategy 處理暫時性資料庫失敗;以及利用 EF Core 7+ 的 ExecuteUpdate/ExecuteDelete 進行高效大量操作。此技能支援 .NET Aspire、ASP.NET Core 等平台,提供清晰的程式碼範例、CLI 命令與常見陷阱說明,幫助開發者避免 N+1 查詢、追蹤衝突及非同步不一致等問題,建立堅固的 EF Core 應用程式。

相容平台~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. 使用 ExecutionStrategy 進行重試 - 處理暫時性資料庫失敗
  5. 明確更新 - 當使用 NoTracking 時,明確標記實體以進行更新

模式 1:預設不追蹤 (NoTracking)

設定您的 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>();
}

當 NoTracking 啟用時

唯讀查詢正常運作:

// ✅ 快速讀取 - 無追蹤開銷
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更有效率

明確 Add/Update 模式

public class OrderService
{
    private readonly ApplicationDbContext _db;

    // CREATE - 永遠使用 Add(無論追蹤狀態都有效)
    public async Task<Order> CreateOrderAsync(Order order)
    {
        _db.Orders.Add(order);
        await _db.SaveChangesAsync();
        return order;
    }

    // UPDATE - 明確標記為已修改
    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();
    }

    // DELETE - 附加並移除
    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("移轉服務正在啟動...");

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

            await RunMigrationsAsync(dbContext, stoppingToken);

            _logger.LogInformation("移轉服務成功完成。");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "移轉服務失敗:{Error}", ex.Message);
            throw;
        }
        finally
        {
            // 移轉完成後停止應用程式
            _hostApplicationLifetime.StopApplication();
        }
    }

    private async Task RunMigrationsAsync(ApplicationDbContext dbContext, CancellationToken ct)
    {
        // 使用 ExecutionStrategy 處理暫時性失敗
        var strategy = dbContext.Database.CreateExecutionStrategy();

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

            if (pendingMigrations.Any())
            {
                _logger.LogInformation("正在套用 {Count} 個擱置的移轉...",
                    pendingMigrations.Count());

                await dbContext.Database.MigrateAsync(ct);

                _logger.LogInformation("移轉成功套用。");
            }
            else
            {
                _logger.LogInformation("沒有擱置的移轉。資料庫已是最新狀態。");
            }
        });
    }
}

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:用於暫時性失敗的 ExecutionStrategy

對於可能暫時性失敗的作業,永遠使用 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 () =>
{
    // 交易必須在 strategy 回呼內部
    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.

相關技能