optimizing-ef-core-queries
できること
このスキルは、.NETのデータベースのライブラリEntity Framework Coreを使うデータアクセスのコードを確認して高速化します。遅いクエリ、多すぎるデータベースの呼び出し、メモリを多く使うデータの読み込みに悩む.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に貼り付けるだけ。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.8kVisual Studio Codeのカスタムエージェントのファイルを、独自のツール、指示、ほかのエージェントへの引き継ぎとともに作るようエージェントを支援します。
create-skill
5.8k有効な名前、明確な発動の説明、規格に従うSKILL.mdファイルを持つ、新しいエージェントのスキルを作るようエージェントを支援します。
csharp-scripts
5.8k.NETのコマンドラインツールを使って、完全なプロジェクトを作らずに、小さなC#のプログラムを一つのファイルとして実行するようエージェントを支援します。
dotnet-pinvoke
5.8k署名、文字列の扱い、メモリ、安全なハンドルを含めて、ネイティブのC言語またはC++のライブラリを.NETから正しく呼び出すようエージェントを支援します。
似ているスキル
api-connector-builder
280kエージェントが既存のパターンに従って、新しいAPI連携を構築します。新しい方式を作らずに、もう一つ連携を追加したいときに使います。
api-design
280kエージェントがベストプラクティスに沿ってREST APIを設計できるようにします。APIの通信方法、エラーの表示方法、データの整理方法を決めるのに役立ちます。
backend-patterns
280kエージェントのサーバーサイドのアーキテクチャパターンとデータベースの最適化を支援します。サーバー上で動くコードを作成またはレビューするときに役立ちます。