Official agent skill

Optimizing Ef Core Queries

by dotnet in dotnet/skills

Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster.

OfficialMITAuto-check passedDatabases

Install Optimizing Ef Core Queries

skills CLI
$ npx skills add dotnet/skills --skill optimizing-ef-core-queries -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install dotnet/skills optimizing-ef-core-queries --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/dotnet/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/dotnet-data/skills/optimizing-ef-core-queries .claude/skills/optimizing-ef-core-queries && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
optimizing-ef-core-queries
GitHub stars
5.6k
Used in
1 other repo
Token cost
~2.7k tokens
SKILL.md length
1,286 words
Files
1
Skills in repo
91
Repo updated
First seen
Licence
MIT

At a glance

Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster.

  • DbContext query
  • SKILL.md covers When to Use, When Not to Use, First: capture the generated SQL and Fixes, plus 2 more sections
  • Calls dotnet
  • Data-access path is slow

What it does

Optimizing Ef Core Queries is an agent skill from dotnet/skills, published by the product's own GitHub organization. Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster. Use whenever an EF Core or DbContext query or data-access path is slow or should be made faster — whether or not EF Core owns the database schema. For EF Core, not Dapper or raw ADO.NET.

Its SKILL.md is about 2.7k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Databases, covering SQL, ORMs and data access and Database schema design. It works with SQL. The repository describes itself as: Repository for skills to assist AI coding agents with .NET and C. The licence is MIT.

When your agent uses it

  • DbContext query
  • Data-access path is slow
  • Should be made faster — whether
  • Not EF Core owns the database schema

Example prompts

  • “/optimizing-ef-core-queries”

What it can do on your machine

Read from SKILL.md and the folder at commit a660de8. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • dotnet

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • learn.microsoft.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Optimizing Ef Core Queries loads about 2.7k tokens when it runs. Until then it costs about 97 tokens; SKILL.md has 1,286 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~97
When it runs · the whole SKILL.md, loaded when a task matches
~2.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from dotnet/skills at commit a660de8, republished under its MIT licence (© dotnet). 1,286 words, ~2,729 tokens.

Download SKILL.mdSave it as .claude/skills/optimizing-ef-core-queries/SKILL.md (or your agent's skills folder).
name
optimizing-ef-core-queries
description
Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster. Use whenever an EF Core or DbContext query or data-access path is slow or should be made faster — whether or not EF Core owns the database schema. For EF Core, not Dapper or raw ADO.NET.
license
MIT

Optimizing EF Core Queries

Diagnose and fix slow Entity Framework Core (EF Core) queries. Start from the generated SQL/logs, apply the smallest change that removes the bottleneck, and confirm the fix by re-reading the SQL and the query count. Prefer changes that reduce round-trips, duplicated rows, scans, or per-call translation cost over micro-optimizations. Apply one change at a time and re-measure.

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 Skip grows, 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 DbContext or recommend AsNoTracking, Include, AsSplitQuery, or other EF Core APIs.

First: capture the generated SQL

You cannot optimize what you cannot see. Turn on command logging and read the SQL and query count before changing anything:

csharp
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

Keep predicates sargable — never wrap an indexed column in a function

An index can only be used when the indexed column appears bare on one side of the comparison. Wrapping it in a function or arithmetic — CreatedAt.Year == y, CreatedAt.Date == d, ToLower(Name) == n, Price * 1.1 > x, or a leading-wildcard LIKE '%foo' — forces a per-row computation the index cannot satisfy, so the query scans the whole table even though the index exists. Adding another index changes nothing. Rewrite the predicate so the column stays bare, usually as a half-open range:

csharp
// Non-sargable: a function is computed for every row → full scan
db.Logs.Where(l => l.CreatedAt.Year == year);

// Sargable: bare column compared to constants → index seek
var start = new DateTime(year, 1, 1);
db.Logs.Where(l => l.CreatedAt >= start && l.CreatedAt < start.AddYears(1));

The same rule covers several common shapes:

  • Case-insensitive text — compare a stored normalized column instead of ToLower(...)/ToUpper(...).
  • Computed expressions — compare against the precomputed constant, not column * k > x.
  • Converting the column to another type — a predicate over column.ToString() (for example matching the text form of a number or date, total.ToString().StartsWith(p)) applies a function to every row and often can't be translated to SQL at all, forcing a client-side evaluation that pulls the whole table into memory. Filter on the typed column with a real comparison or range instead.
  • Substring search — name.Contains(term) becomes an unanchored LIKE '%term%' that can't seek an index and scans the table; a trailing-wildcard prefix (name.StartsWith(term) → 'term%') can seek. Anchor the search when a prefix match is acceptable — this changes which rows match, so confirm the behavior first — and put real substring or fuzzy search behind a full-text index on large tables.

Verify: the plan shows a seek/index instead of a scan and duration drops. If the column genuinely has no index, add one (see below) — but only after the predicate is sargable.

Compile hot, frequently-executed queries

On a very hot path that runs the same query shape thousands of times over a reused context, EF Core re-parses the LINQ expression tree and probes its query cache on every call. When the query is already minimal (an indexed lookup or a small projection) and read-only tweaks such as AsNoTracking buy nothing, that per-call translation is the remaining cost. Compile the query once with EF.CompileQuery / EF.CompileAsyncQuery and reuse the delegate:

csharp
private static readonly Func<AppDbContext, int, ProductListItem> GetProduct =
    EF.CompileQuery((AppDbContext db, int id) =>
        db.Products.Where(p => p.Id == id)
                   .Select(p => new ProductListItem(p.Id, p.Name, p.Price))
                   .First());

public ProductListItem Lookup(AppDbContext db, int id) => GetProduct(db, id);

The delegate is static (compiled once) and takes the DbContext plus each parameter as arguments. Use it for endpoints or loops that execute one query shape at very high frequency; it does nothing for one-off queries.

Verify: the hot loop's mean time drops with identical results.

Remove N+1 and avoid lazy loading

The same SELECT repeated once per row (a navigation accessed inside a loop) is an N+1. Load the related data in one round-trip — project the aggregates with Select, or eager-load with Include:

csharp
var summaries = await db.Orders
    .Select(o => new OrderSummary(o.Id, o.Items.Count, o.Items.Sum(i => i.Price)))
    .ToListAsync();

Prefer projection or Include over lazy loading: lazy loading is a leading cause of N+1 and forces synchronous I/O. In server apps, don't enable Microsoft.EntityFrameworkCore.Proxies or mark navigations virtual for lazy loading.

Verify: a fixed, small query count regardless of row count.

Split multiple collection Includes

Includeing two or more collection navigations in one query multiplies rows (a Cartesian explosion) and duplicates parent data. Use AsSplitQuery() so each collection loads in its own statement; add OrderBy on a unique key so rows stitch together:

csharp
db.Blogs.Include(b => b.Posts).Include(b => b.Contributors).AsSplitQuery();

Verify: rows per statement drop sharply and total duration improves.

Show full SKILL.md (536 more words)Show less
Filter and paginate; prefer keyset over offset

Constrain large result sets with Where, and page with keyset (seek) pagination rather than Skip/Take, which still scans and discards the skipped rows on deep pages:

csharp
db.Orders.Where(o => o.Id > lastSeenId).OrderBy(o => o.Id).Take(pageSize);

Order by a unique, stable, indexed key (add tie-breakers if the sort column isn't unique). Keyset pages by the last key seen rather than a page number, so it changes the method's inputs; when a fixed signature rules out an in-place switch, still flag the deep-offset scan and recommend keyset.

Verify: page latency stays roughly constant from early to deep pages.

Add missing indexes

Moving a filter into SQL or making a predicate sargable stops the client-side waste, but a WHERE or ORDER BY on a column with no index still scans the whole table inside the database — and a frequently-run query then re-scans it on every call. So audit index coverage separately from the query rewrite: for each query, check whether its filter and sort columns are backed by an index. Entity keys and foreign keys are indexed by convention, but other columns — status flags, state/enum fields, timestamps, names — usually are not unless the model configures it. When a hot query filters or sorts on such an unindexed column, recommend adding an index and say so explicitly, even when the rewritten query already returns the right rows: the index is a separate fix the code change alone doesn't deliver. (If the predicate isn't sargable, fix that first — a new index can't help a scan caused by a function on the column.)

If EF Core owns the schema, add the index in the model and migrate:

csharp
modelBuilder.Entity<Order>()
    .HasIndex(o => new { o.CustomerId, o.CreatedAt }); // equality column first, then range/sort

Then create the migration with dotnet ef migrations add .... Do not apply it with dotnet ef database update (or any equivalent that writes to the database) without explicit user approval — applying a migration mutates the database, so add the migration, show it to the user, and let them run the update once they've reviewed it. If EF Core does not own the schema, recommend the same index to whoever manages the database. Don't over-index — every index slows writes.

Verify: the plan uses a seek/index instead of a scan.

Set-based bulk updates and deletes

Replace a load-mutate-SaveChanges loop with ExecuteUpdateAsync/ExecuteDeleteAsync (EF Core 7+) — one statement, no entities materialized:

csharp
await db.Products.Where(p => p.LastSoldDate < cutoff)
    .ExecuteUpdateAsync(s => s.SetProperty(p => p.IsActive, false));

These bypass the change tracker and EF-side cascade behavior — apply related changes explicitly.

Verify: a single UPDATE/DELETE with a WHERE and no preceding SELECT.

Common Pitfalls

PitfallFix
Wrapping an indexed column in .Year/.Date/ToLower/arithmeticRewrite to a sargable range/comparison on the bare column
Adding an index to fix a scan on a non-sargable predicateFix the predicate first; the index can't help until the column is bare
Rewriting a filter into SQL but leaving a hot query on an unindexed columnThe server-side scan is still a scan — recommend an index on the filter/sort column too
Compiling a query that runs only occasionallyCompile only genuinely hot, high-frequency query shapes
Lazy loading (proxies / virtual navigations) causing N+1 and forced sync I/OEager-load (Include) or project; keep queries async
ToList()/AsEnumerable() before Where/SelectKeep the query IQueryable so filtering/projection run in SQL

References

© dotnet, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in plugins/dotnet-data/skills/optimizing-ef-core-queries of dotnet/skills.

Open the folder on GitHubat commit a660de8

Used in 1 other repository

We found 2 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 1 other GitHub owner. This page covers the copy in dotnet/skills, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Optimizing Ef Core Queries next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Optimizing Ef Core Queries compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Optimizing Ef Core Queries this skilldotnet/skills5.6k1 repos~2.7kAutomated safety check: PassMIT
DB Migrationskurealnum/dotfiles290—~820Automated safety check: PassNone
Migrationkortix-ai/suna20k—~1.2kAutomated safety check: PassCustom licence
Database FundamentalsDanielPodolsky/ownyourcode2901 repos~1.6kAutomated safety check: PassMIT
Drizzle Orm D1secondsky/claude-skills227—~2.4kAutomated safety check: PassMIT
SQL ToolkitLeoYeAI/openclaw-master-skills2.2k—~3kAutomated safety check: PassMIT

Similar skills

  • DB Migrations

    kurealnum/dotfiles

    A skill your agent uses when generating or regenerating Drizzle migration files, changing database schema tables or columns, resolving migration sequence conflicts after rebase, reviewing migration…

    290 GitHub stars~820 tokensUpdated 5 mo ago
    DatabasesAuto-check passed
  • Migration

    kortix-ai/suna

    How to change the database schema in this repo. An agent skill from kortix-ai/suna.

    20k GitHub stars~1.2k tokensUpdated today
    DatabasesAuto-check passed
  • Database Fundamentals

    DanielPodolsky/ownyourcode

    Reviews schema design, SQL queries, ORM patterns. An agent skill from DanielPodolsky/ownyourcode.

    290 GitHub starsUsed in 1 repo~1.6k tokens
    DatabasesAuto-check passed
  • Drizzle Orm D1

    secondsky/claude-skills

    | Type-safe ORM for Cloudflare D1 databases using Drizzle. An agent skill from secondsky/claude-skills.

    227 GitHub stars~2.4k tokensUpdated 10 days ago
    DatabasesAuto-check passed
  • SQL Toolkit

    LeoYeAI/openclaw-master-skills

    Query, design, migrate, and optimize SQL databases. An agent skill from LeoYeAI/openclaw-master-skills.

    2.2k GitHub stars~3k tokensUpdated 2 mo ago
    DatabasesAuto-check passed
  • Tsh SQL And Database Understanding

    TheSoftwareHouse/copilot-collections

    SQL writing and database engineering patterns, standards, and procedures.

    284 GitHub stars~11k tokensUpdated 3 days ago
    DatabasesAuto-check passed

More from dotnet/skills

All 91 skills in this repo
  • Official

    Resolves .NET runtime frames in Apple .ips crash logs to function names, source files and line numbers using dSYM symbols, atos and the Microsoft symbol server.

    5.6k GitHub starsUsed in 1 repo~2.4k tokens
    Auto-check passed
  • Official

    Resolves native crash frames from .NET Android tombstones to function names, source files and line numbers using BuildIds, Microsoft's symbol server and llvm-symbolizer.

    5.6k GitHub starsUsed in 1 repo~2.1k tokens
    Auto-check passed
  • Official

    Scans C# and .NET code for about 50 performance anti-patterns and reports prioritized findings with concrete fixes, at a scan depth you choose.

    5.6k GitHub starsUsed in 3 repos~3.1k tokens
    Auto-check passed
  • Official

    Statically pairs source files with test files to list code that no test references, using Roslyn for C# or tree-sitter for many languages, with no build.

    5.6k GitHub starsUsed in 1 repo~3.3k tokens
    Auto-check passed
  • Microbenchmarking

    dotnet/skills

    Official

    Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, running, configuring, or reviewing BDN benchmarks.

    5.6k GitHub starsUsed in 3 repos~3.3k tokens
    Auto-check passed
  • Official

    Makes .NET projects compatible with Native AOT and trimming by resolving IL trim and AOT analyzer warnings through annotations rather than suppressions.

    5.6k GitHub starsUsed in 2 repos~4.2k tokens
    Auto-check passed

Works with

Categories

Questions about Optimizing Ef Core Queries

What does Optimizing Ef Core Queries do?

Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster. Optimizing Ef Core Queries is an agent skill from dotnet/skills, published by the product's own GitHub organization. Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster.

When should I use Optimizing Ef Core Queries?

Optimizing Ef Core Queries fits situations like: dbContext query; data-access path is slow; should be made faster — whether; not EF Core owns the database schema.

How do I install Optimizing Ef Core Queries in Claude Code?

Run `npx skills add dotnet/skills --skill optimizing-ef-core-queries -a claude-code`. Or copy the skill folder (plugins/dotnet-data/skills/optimizing-ef-core-queries in dotnet/skills) into .claude/skills/optimizing-ef-core-queries in your project. Claude Code loads it when a task matches its description.

How do I install Optimizing Ef Core Queries in Codex?

Run `npx skills add dotnet/skills --skill optimizing-ef-core-queries -a codex`. Or copy the skill folder (plugins/dotnet-data/skills/optimizing-ef-core-queries in dotnet/skills) into .agents/skills/optimizing-ef-core-queries in your project. Codex loads it when a task matches its description.

Can I use Optimizing Ef Core Queries in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add dotnet/skills --skill optimizing-ef-core-queries -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/optimizing-ef-core-queries, .gemini/skills/optimizing-ef-core-queries, .github/skills/optimizing-ef-core-queries and .opencode/skills/optimizing-ef-core-queries in your project.

What does Optimizing Ef Core Queries need to run?

Going by SKILL.md and its folder, Optimizing Ef Core Queries needs the command-line tools its instructions call (dotnet).

Does Optimizing Ef Core Queries access the network?

SKILL.md names 1 domain. As links in the text: learn.microsoft.com. This is read from the text; nothing was executed.

Is Optimizing Ef Core Queries safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Optimizing Ef Core Queries use?

Optimizing Ef Core Queries is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Optimizing Ef Core Queries use?

About 2.7k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Optimizing Ef Core Queries?

Skills that share tags, products or a category with Optimizing Ef Core Queries: DB Migrations (kurealnum/dotfiles, 290 stars), Migration (kortix-ai/suna, 20k stars), Database Fundamentals (DanielPodolsky/ownyourcode, 290 stars) and Drizzle Orm D1 (secondsky/claude-skills, 227 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Optimizing Ef Core Queries?

dotnet (a GitHub organization, an official publisher) maintains it in dotnet/skills, which has 5,576 GitHub stars. The repository holds 91 skills in this directory. The repository was last updated on October 8, 2026.

Source: dotnet/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.