Community编程与开发github.com

数据库性能

数据库访问性能模式。分离读写模型、避免 N+1 查询、使用 AsNoTracking、应用行数限制,并且永远不要在应用层进行连接操作。适用于 EF Core 和 Dapper。

数据库性能 是什么?

这个技能(Skill)针对.NET开发者,尤其是使用EF Core或Dapper构建数据访问层项目的开发者,提供了系统化的数据库性能优化方案。它详细介绍了读写模型分离(CQRS模式)、N+1查询避免、行数限制应用、AsNoTracking使用、避免应用层连接及笛卡尔积爆炸等核心模式。该技能包含大量可直接使用的C#代码示例,以及清晰的最佳实践和反模式对比。它同时对DOs和DON'Ts进行了明确阐述,帮助开发者编写高性能、可维护且可扩展的数据访问代码。

兼容平台~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
  • 读取查询是无状态的投影 - 无需跟踪
  • 写入操作侧重于命令验证,而不是之后检索数据
  • 不同的数据库/表可以支持读取 vs 写入(最终一致性模式)

始终应用行数限制

永远不要返回无界的结果集。 每个读取方法都应该有一个可配置的限制。

模式:Limit 参数

public interface IOrderReadStore
{
    // Limit 是必需的,而不是可选的
    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 vs 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.

相关技能