optimizing-ef-core-queries
하는 일
이 스킬은 Entity Framework Core를 쓰는 데이터 접근 코드를 검토하고 빠르게 만듭니다. 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에 붙여넣으세요. 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++ 라이브러리를 올바르게 호출하도록 돕습니다. 시그니처, 문자열 처리, 메모리, 안전 핸들을 다룹니다.
비슷한 스킬
api-connector-builder
280k에이전트가 기존 패턴을 따라 새로운 API 연결을 만들도록 합니다. 새로운 방식을 도입하지 않고 연동을 하나 더 추가할 때 씁니다.
api-design
280k에이전트가 모범 사례에 따라 REST API를 설계하도록 돕습니다. API가 통신하는 방식, 오류를 보여 주는 방식, 데이터를 정리하는 방식을 정하는 데 유용합니다.
backend-patterns
280k에이전트가 서버 쪽 아키텍처 패턴과 데이터베이스 최적화를 다루도록 돕습니다. 서버에서 실행되는 코드를 만들거나 검토할 때 유용합니다.