Community程式設計與開發github.com

資料庫效能模式

資料庫存取模式以提升效能。分離讀寫模型、避免 N+1 查詢、使用 AsNoTracking、設定資料列限制,且絕不在應用端進行關聯。支援 EF Core 和 Dapper。

資料庫效能模式 是什麼?

這個「資料庫效能模式」AI 助手技能提供了一套清晰的資料存取層設計原則,專注於使用 .NET 技術(如 EF Core 和 Dapper)打造高效能的資料庫操作。它強調將讀取與寫入模型分離(CQRS 模式),為不同使用案例建立專門的投影,而非共用單一實體。此技能詳細說明如何避免常見的效能陷阱,包括總是強制設定可設定的資料列限制、在唯讀查詢中使用 AsNoTracking 以節省 EF Core 的變更追蹤開銷、利用 Include 或批次查詢解決 N+1 查詢問題,以及嚴格在 SQL 中進行關聯,絕不在應用程式層級進行。此外,它還介紹了利用 AsSplitQuery 或顯式投影來避免笛卡兒乘積爆炸、約束資料庫欄位大小以避免過大資料,並提供了指導方針,讓開發者根據情境(簡單 CRUD 用 EF Core,複雜唯讀查詢用 Dapper)在單一專案中靈活混合使用兩種技術。

相容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/database-performance

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

資料庫效能模式 是做什麼的?

何時使用此技能

當您需要以下情況時,請使用此技能:

  • 設計資料存取層
  • 優化緩慢的資料庫查詢
  • 在 EF Core 和 Dapper 之間做選擇
  • 避免常見的效能陷阱

核心原則

  1. 分離讀取和寫入模型 - 不要對兩者使用相同的類型
  2. 批次思考 - 避免 N+1 查詢
  3. 只取所需 - 不要使用 SELECT *
  4. 設定資料列限制 - 始終有可設定的 Take/Limit
  5. 在 SQL 中進行關聯 - 絕不在應用程式程式碼中進行
  6. 為讀取查詢使用 AsNoTracking - EF Core 變更追蹤成本高昂

讀取/寫入模型分離(CQRS 模式)

**讀取和寫入模型本質上是不同的——它們有不同的形狀、資料行和用途。**不要建立單一的「User」實體然後到處重複使用。

  • 讀取模型是反正規化的,針對查詢效率最佳化,並回傳多種投影類型(UserProfile、UserSummary、UserDetailForAdmin)
  • 寫入模型是正規化的,專注於驗證,並接受強型別的指令(CreateUserCommand、UpdateUserCommand)

架構

src/
  MyApp.Data/
    Users/
      # 讀取端 - 多個最佳化的投影
      IUserReadStore.cs
      PostgresUserReadStore.cs

      # 寫入端 - 指令處理器
      IUserWriteStore.cs
      PostgresUserWriteStore.cs

      # 讀取 DTO - 輕量級,反正規化
      UserProfile.cs
      UserSummary.cs

      # 寫入指令 - 專注於驗證
      CreateUserCommand.cs
      UpdateUserCommand.cs
    Orders/
      IOrderReadStore.cs
      IOrderWriteStore.cs
      (類似的結構...)

讀取存放介面

// 讀取模型:針對不同使用案例最佳化的多種專門投影
public interface IUserReadStore
{
    // 回傳單一使用者檢視的詳細資訊檔
    Task<UserProfile?> GetByIdAsync(UserId id, CancellationToken ct = default);

    // 回適用於查詢的輕量級資訊
    Task<UserProfile?> GetByEmailAsync(EmailAddress email, CancellationToken ct = default);

    // 回傳分頁摘要 - 僅列表檢視所需的資料
    Task<IReadOnlyList<UserSummary>> GetAllAsync(int limit, UserId? cursor = null, CancellationToken ct = default);

    // 布林查詢 - 不需要實體
    Task<bool> EmailExistsAsync(EmailAddress email, CancellationToken ct = default);
}

寫入存放介面

// 寫入模型:接受強型別指令,回傳最小值
public interface IUserWriteStore
{
    // 僅回傳建立的 ID - 呼叫者不需要完整的實體
    Task<UserId> CreateAsync(CreateUserCommand command, CancellationToken ct = default);

    // 更新驗證指令,回傳 void(成功或擲出例外)
    Task UpdateAsync(UserId id, UpdateUserCommand command, CancellationToken ct = default);

    // 刪除操作簡單明確
    Task DeleteAsync(UserId id, CancellationToken ct = default);
}

說明的關鍵結構差異:

  • 讀取存放回傳多個不同的 DTO(UserProfile、UserSummary、bool 旗標)
  • 寫入存放回傳最小資料(僅在建立時回傳 UserId)或 void
  • 讀取查詢是無狀態的投影 - 不需要追蹤
  • 寫入操作專注於指令驗證,而不是之後檢索資料
  • 不同的資料庫/資料表可以支援讀取與寫入(最終一致性模式)

始終設定資料列限制

**絕不回傳無限制的結果集。**每個讀取方法都應有可設定的限制。

模式:Limit 參數

public interface IOrderReadStore
{
    // 限制是必要的,而非選擇性
    Task<IReadOnlyList<OrderSummary>> GetByCustomerAsync(
        CustomerId customerId,
        int limit,
        OrderId? cursor = null,
        CancellationToken ct = default);
}

// 實作
public async Task<IReadOnlyList<OrderSummary>> GetByCustomerAsync(
    CustomerId customerId,
    int limit,
    OrderId? cursor = null,
    CancellationToken ct = default)
{
    await using var connection = await _dataSource.OpenConnectionAsync(ct);

    const string sql = """
        SELECT id, customer_id, total, status, created_at
        FROM orders
        WHERE customer_id = @CustomerId
        AND (@Cursor IS NULL OR created_at < (SELECT created_at FROM orders WHERE id = @Cursor))
        ORDER BY created_at DESC
        LIMIT @Limit
        """;

    var rows = await connection.QueryAsync<OrderRow>(sql, new
    {
        CustomerId = customerId.Value,
        Cursor = cursor?.Value,
        Limit = limit
    });

    return rows.Select(r => r.ToOrderSummary()).ToList();
}

使用 EF Core 進行分頁

public async Task<PaginatedList<OrderSummary>> GetOrdersAsync(
    CustomerId customerId,
    Paginator paginator,
    CancellationToken ct = default)
{
    var query = _context.Orders
        .AsNoTracking()
        .Where(o => o.CustomerId == customerId.Value)
        .OrderByDescending(o => o.CreatedAt);

    var totalCount = await query.CountAsync(ct);

    var orders = await query
        .Skip((paginator.PageNumber - 1) * paginator.PageSize)
        .Take(paginator.PageSize)  // 務必設定限制!
        .Select(o => new OrderSummary(
            new OrderId(o.Id),
            o.Total,
            o.Status,
            o.CreatedAt))
        .ToListAsync(ct);

    return new PaginatedList<OrderSummary>(
        orders,
        totalCount,
        paginator.PageSize,
        paginator.PageNumber);
}

為讀取查詢使用 AsNoTracking

EF Core 的變更追蹤成本高昂。請在唯讀查詢中停用它。

// 正確做法:為讀取查詢停用追蹤
var users = await _context.Users
    .AsNoTracking()
    .Where(u => u.IsActive)
    .ToListAsync();

// 錯誤做法:追蹤您不會修改的實體
var users = await _context.Users
    .Where(u => u.IsActive)
    .ToListAsync();  // 變更追蹤已啟用 - 浪費資源

設定預設行為

// 對於讀取密集型應用程式,請考慮在 DbContext 中這樣做
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
}

然後在需要時明確啟用追蹤:

var user = await _context.Users
    .AsTracking()  // 明確啟用 - 我們打算修改
    .FirstOrDefaultAsync(u => u.Id == userId);

避免 N+1 查詢

N+1 問題:先擷取一個列表,然後對每個項目的相關資料進行查詢。

問題範例

// 錯誤做法:N+1 查詢
var orders = await _context.Orders.ToListAsync();

foreach (var order in orders)
{
    // 每次迭代都會存取資料庫!
    var items = await _context.OrderItems
        .Where(i => i.OrderId == order.Id)
        .ToListAsync();
}

解決方案 1:Include(EF Core)

// 正確做法:使用關聯的單一查詢
var orders = await _context.Orders
    .AsNoTracking()
    .Include(o => o.Items)
    .ToListAsync();

解決方案 2:批次查詢(Dapper)

// 正確做法:兩次查詢,沒有 N+1
const string sql = """
    SELECT id, customer_id, total FROM orders WHERE customer_id = @CustomerId;
    SELECT oi.* FROM order_items oi
    INNER JOIN orders o ON oi.order_id = o.id
    WHERE o.customer_id = @CustomerId;
    """;

using var multi = await connection.QueryMultipleAsync(sql, new { CustomerId = customerId });
var orders = (await multi.ReadAsync<OrderRow>()).ToList();
var items = (await multi.ReadAsync<OrderItemRow>()).ToList();

// 在記憶體中進行關聯(可接受 - 資料已擷取)
foreach (var order in orders)
{
    order.Items = items.Where(i => i.OrderId == order.Id).ToList();
}

絕不在應用端進行關聯

關聯必須在 SQL 中進行,而不是在 C# 中。

// 錯誤做法:應用端關聯 - 兩次查詢,浪費記憶體
var customers = await _context.Customers.ToListAsync();
var orders = await _context.Orders.ToListAsync();

var result = customers.Select(c => new
{
    Customer = c,
    Orders = orders.Where(o => o.CustomerId == c.Id).ToList()  // 在記憶體中執行 O(n*m)!
});

// 正確做法:SQL 關聯 - 單一查詢
var result = await _context.Customers
    .AsNoTracking()
    .Include(c => c.Orders)
    .ToListAsync();

// 正確做法:明確的關聯(Dapper)
const string sql = """
    SELECT c.id, c.name, COUNT(o.id) as order_count
    FROM customers c
    LEFT JOIN orders o ON c.id = o.customer_id
    GROUP BY c.id, c.name
    """;

避免笛卡兒乘積爆炸

多次呼叫 Include 可能導致笛卡兒乘積。

// 危險:可能爆炸成數百萬行
var product = await _context.Products
    .Include(p => p.Reviews)      // 100 筆評論
    .Include(p => p.Images)       // 20 張圖片
    .Include(p => p.Categories)   // 5 個分類
    .FirstOrDefaultAsync(p => p.Id == id);
// 結果:100 * 20 * 5 = 10,000 行資料被傳輸!

解決方案:分割查詢

// 正確做法:多次查詢,沒有笛卡兒乘積爆炸
var product = await _context.Products
    .AsSplitQuery()
    .Include(p => p.Reviews)
    .Include(p => p.Images)
    .Include(p => p.Categories)
    .FirstOrDefaultAsync(p => p.Id == id);
// 結果:4 個獨立的查詢,總共約 125 行

解決方案:明確投影

// 最佳做法:只取出所需的資料
var product = await _context.Products
    .AsNoTracking()
    .Where(p => p.Id == id)
    .Select(p => new ProductDetail(
        p.Id,
        p.Name,
        p.Description,
        p.Reviews.OrderByDescending(r => r.CreatedAt).Take(10).ToList(),
        p.Images.Take(5).ToList(),
        p.Categories.Select(c => c.Name).ToList()))
    .FirstOrDefaultAsync();

約束資料行大小

在您的 EF Core 模型中定義最大長度,以防止資料過大。

public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.Property(u => u.Email)
            .HasMaxLength(254)  // RFC 5321 限制
            .IsRequired();

        builder.Property(u => u.Name)
            .HasMaxLength(100)
            .IsRequired();

        builder.Property(u => u.Bio)
            .HasMaxLength(500);

        // 對於真正的大型內容,請明確使用 text 類型
        builder.Property(u => u.Notes)
            .HasColumnType("text");
    }
}

不要建立泛型儲存庫

泛型儲存庫會隱藏查詢複雜性,使最佳化變得困難。

// 錯誤做法:泛型儲存庫
public interface IRepository<T>
{
    Task<T?> GetByIdAsync(int id);
    Task<IEnumerable<T>> GetAllAsync();  // 沒有限制!
    Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);  // 無法最佳化
}

// 正確做法:專用讀取存放
public interface IOrderReadStore
{
    Task<OrderDetail?> GetByIdAsync(OrderId id, CancellationToken ct = default);
    Task<IReadOnlyList<OrderSummary>> GetByCustomerAsync(CustomerId id, int limit, CancellationToken ct = default);
    Task<IReadOnlyList<OrderSummary>> GetPendingAsync(int limit, CancellationToken ct = default);
}

泛型儲存庫的問題:

  • 無法最佳化特定查詢
  • 無法強制限制
  • 隱藏 N+1 問題
  • 容易擷取過多資料
  • 鼓勵對資料存取懶散思考

針對讀取密集型工作負載使用 Dapper

對於複雜的讀取查詢,使用明確 SQL 的 Dapper 通常更簡潔且更快速。

public sealed class PostgresUserReadStore : IUserReadStore
{
    private readonly NpgsqlDataSource _dataSource;

    public PostgresUserReadStore(NpgsqlDataSource dataSource)
    {
        _dataSource = dataSource;
    }

    public async Task<UserProfile?> GetByIdAsync(UserId id, CancellationToken ct = default)
    {
        await using var connection = await _dataSource.OpenConnectionAsync(ct);

        const string sql = """
            SELECT id, email, name, bio, created_at
            FROM users
            WHERE id = @Id
            """;

        var row = await connection.QuerySingleOrDefaultAsync<UserRow>(
            sql, new { Id = id.Value });

        return row?.ToUserProfile();
    }

    // 用於 Dapper 對應的內部資料列類型
    private sealed class UserRow
    {
        public Guid id { get; set; }
        public string email { get; set; } = null!;
        public string name { get; set; } = null!;
        public string? bio { get; set; }
        public DateTime created_at { get; set; }

        public UserProfile ToUserProfile() => new(
            Id: new UserId(id),
            Email: new EmailAddress(email),
            Name: new PersonName(name),
            Bio: bio,
            CreatedAt: new DateTimeOffset(created_at, TimeSpan.Zero));
    }
}

何時使用 EF Core 與 Dapper

情境建議
簡單的 CRUDEF Core
複雜的讀取查詢Dapper
含驗證的寫入操作EF Core
大量操作Dapper 或純 SQL
報表/分析Dapper
領域密集型寫入EF Core

您可以在同一個專案中同時使用兩者 - EF Core 用於寫入,Dapper 用於讀取。


快速參考

反模式解決方案
無資料列限制為每個讀取方法新增 limit 參數
SELECT *僅投影需要的資料行
N+1 查詢使用 Include 或批次查詢
應用端關聯在 SQL 中進行關聯
笛卡兒乘積爆炸使用 AsSplitQuery 或投影
追蹤唯讀資料使用 AsNoTracking
泛型儲存庫專用的讀取/寫入存放
無限制的字串在模型中設定 MaxLength

資源

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.

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.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

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.

相關技能