optimizing-ef-core-queries
它能做什么
这项技能审阅并加速使用 Entity Framework Core(.NET 数据库库)的数据访问代码。适合查询缓慢、数据库调用过多或数据加载占用大量内存的 .NET 开发者。
适用场景
- ✓当 Entity Framework 查询很慢,或发送的 SQL 比预期多得多的时候。
- ✓当同一个查询对每一行各执行一次,即 N+1 问题出现时。
- ✓当多个 include 导致重复行,或批量更新很慢的时候。
技能链接
https://github.com/dotnet/skills/blob/main/plugins/dotnet-data/skills/optimizing-ef-core-queries/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“我的 EF Core 列表页面运行了几百个查询。请找出原因并修复。”
每周 5 个新技能,1 分钟读完。
工作原理
智能体会在不运行代码的情况下追踪数据访问代码,找出多余往返和重复行的来源,并提出减少数据库工作量的修改方案,并在可用时用 SQL 或执行计划进行核对。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Optimizing EF Core Queries
Diagnose and fix slow or incorrect application data access built on EF Core. In a source-only review, trace the code without executing it and separate proven code behavior from runtime assumptions. When SQL, logs, or plans are available, use them to confirm the bottleneck. Prefer changes that reduce round-trips, duplicated rows, scans, or per-call translation cost over micro-optimizations.
When to Use
- EF Core queries are slow or emit far more SQL statements than expected
- The same query repeats once per row (N+1 / lazy loading)
- Multiple collection
Includes blow up or duplicate rows - Deep pages slow down as
Skipgrows, or bulk updates load rows just to modify them - A filtered/sorted query scans even though the column is indexed, or a filtered/sorted column has no supporting index
- A hot, frequently-executed query pays EF Core's LINQ-translation cost on every call
When Not to Use
- The code uses Dapper or raw ADO.NET, not EF Core. Answer the SQL/indexing/query-plan question directly; do not introduce a
DbContextor recommendAsNoTracking,Include,AsSplitQuery, or other EF Core APIs.
Source review workflow
- Find the EF boundary:
DbContext,DbSet, repository implementation, unit of work, query helper, or model-building code. Follow the implementation rather than assuming what an interface method does. - Trace each query to execution or enumeration. Check whether operators bind to
QueryableorEnumerable, including inside helpers; anIEnumerablecan remain a deferred database sequence. - Count database operations and actual transaction boundaries along the calling path, including immediate writes and repeated enumeration. Also track which operations share the same
DbContextinstance - For every execution path, independently inspect predicates, expression construction, projection contents, result bounds, ordering, Includes, tracking, SQL parameterization, and model-building code.
- Preserve the contract: result membership and order, random-page access, generated keys, retries, transaction and partial-failure behavior, concurrency handling, and domain/interceptor side effects.
- Report prioritized findings with locations, the affected call path, concrete impact, and a safe remedy. Briefly identify sound counterparts and state what was not validated. Do not equate source reasoning with measured plans or speedups.
For a source-only request, recommend runtime validation as a next step.
For raw SQL, prefer EF Core's interpolated overloads (FromSql / FromSqlInterpolated and ExecuteSql[Async]) so values are sent as parameters.
Gate source-only findings on evidence
When the user requests a source-only review, distinguish a demonstrated defect from an optimization that still needs workload or deployment evidence:
- A load-mutate loop followed by one
SaveChanges[Async]is notSaveChangesin a loop. Do not call it a per-row round-trip defect; suggest a bulk API only when the operation is demonstrably large and bypassing tracking semantics is safe. - Missing
HasIndexcalls in one supplied file do not prove that the deployed database lacks indexes. Use relevant model-building code, migrations, or a query plan as evidence. Do not pad a source review with generic conditional index advice when that evidence is absent. - Missing
AsNoTrackingis actionable only on proven read-only entity results. Scalar-only projections have nothing to track, but an entity inside a DTO/record is still tracked by default. - If every reviewed pattern is sound, say that no actionable changes are needed rather than manufacturing a finding.
Capture SQL and query counts
Use supplied logs and plans first. For an executable investigation, enable command logging to verify query shape and count before and after a change:
optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);
// or set "Microsoft.EntityFrameworkCore.Database.Command": "Information" in appsettings.json
Tag a query with .TagWith("...") to find it in the log. Count how many statements a slow operation runs, and how many rows each returns, before and after each change.
Fixes
Trace materialization and result bounds
Materialization inside a helper is still an execution boundary. A list or array has already loaded rows; later reductions run in memory. An IEnumerable<T> can instead hide a deferred EF query: its Enumerable operators process rows locally
常见问题
它适用于 Dapper 吗?
不适用。对于使用 Dapper 或原始 SQL 的代码,它只回答查询相关的问题,不提供 EF Core 的建议。
它会运行代码吗?
在源代码审阅中,它会在不运行代码的情况下进行追踪;如果有 SQL 日志或执行计划,则会加以使用。
它只做细微的调整吗?
不。它优先选择减少往返次数、重复行或全表扫描的改动,而不是小型的微优化。
详情
作者的原始描述
Review and optimize application data access that uses Entity Framework Core (EF Core). Use for EF Core performance and correctness reviews of services, repositories, imports, and background jobs: slow or memory-heavy queries, excessive round-trips, hidden SaveChanges, premature materialization, dynamic query construction, result-graph tracking, bulk writes, DbContext lifetime or overlapping operations, search semantics, paging, raw SQL, and model/index coverage. Use whether or not EF Core owns the schema. For EF Core, not Dapper or raw ADO.NET.
repo: dotnet/skills
热度
- GitHub 星标
- 5.8k
- 排名
- #14572
- 许可证
- MIT
- 更新时间
- 2026/11/2
评论
- …
同一仓库的更多技能
create-custom-agent
5.8k帮你的智能体创建 VS Code 自定义智能体文件,为每个智能体设置专属工具、指令以及向其他智能体的交接。
create-skill
5.8k帮你的智能体创建新的智能体技能,包括有效的名称、清晰的触发描述,以及符合标准的 SKILL.md 文件。
csharp-scripts
5.8k帮你的智能体通过 .NET 命令行工具以单个文件运行小型 C# 程序,无需创建完整项目。
dotnet-pinvoke
5.8k帮你的智能体在 .NET 中正确调用原生 C 或 C++ 库,涵盖函数签名、字符串处理、内存和安全句柄。