[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CVG5P76V22DMWS2W5TZDGF":3,"skill-same:01M7CVG5P76V22DMWS2W5TZDGF":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":13,"repositoryHtmlUrl":26,"repositoryHomepageUrl":6,"ownerHtmlUrl":27,"ownerBlogUrl":28,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M7CVG5P76V22DMWS2W5TZDGF","optimizing-ef-core-queries",null,"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\u002Findex coverage. Use whether or not EF Core owns the schema. For EF Core, not Dapper or raw ADO.NET.","deadmade\u002Fdead-agent-skills","deadmade","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F130925709?v=4","01M7CTQ65AGYR4J9K9TX0YR9V3","01M7CTQ66B4VMJFEDZP4EKKE6K",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Foptimizing-ef-core-queries\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: optimizing-ef-core-queries\ndescription: \"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\u002Findex coverage. Use whether or not EF Core owns the schema. For EF Core, not Dapper or raw ADO.NET.\"\nlicense: MIT\n---\n\n# Optimizing EF Core Queries\n\nDiagnose 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.\n\n## When to Use\n\n- EF Core queries are slow or emit far more SQL statements than expected\n- The same query repeats once per row (N+1 \u002F lazy loading)\n- Multiple collection `Include`s blow up or duplicate rows\n- Deep pages slow down as `Skip` grows, or bulk updates load rows just to modify them\n- A filtered\u002Fsorted query scans **even though the column is indexed**, or a filtered\u002Fsorted column has no supporting index\n- A hot, frequently-executed query pays EF Core's LINQ-translation cost on every call\n\n## When Not to Use\n\n- **The code uses Dapper or raw ADO.NET, not EF Core.** Answer the SQL\u002Findexing\u002Fquery-plan question directly; do not introduce a `DbContext` or recommend `AsNoTracking`, `Include`, `AsSplitQuery`, or other EF Core APIs.\n\n## Source review workflow\n\n1. 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.\n2. Trace each query to execution or enumeration. Check whether operators bind to `Queryable` or `Enumerable`, including inside helpers; an `IEnumerable` can remain a deferred database sequence.\n3. Count database operations and actual transaction boundaries along the calling path, including immediate writes and repeated enumeration. Also track which operations share the same `DbContext` instance\n4. For every execution path, independently inspect predicates, expression construction, projection contents, result bounds, ordering, Includes, tracking, SQL parameterization, and model-building code.\n5. Preserve the contract: result membership and order, random-page access, generated keys, retries, transaction and partial-failure behavior, concurrency handling, and domain\u002Finterceptor side effects.\n6. 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.\n\nFor a source-only request, recommend runtime validation as a next step.\n\nFor raw SQL, prefer EF Core's interpolated overloads (`FromSql` \u002F `FromSqlInterpolated` and `ExecuteSql[Async]`) so values are sent as parameters.\n\n## Gate source-only findings on evidence\n\nWhen the user requests a source-only review, distinguish a demonstrated defect from an optimization that still needs workload or deployment evidence:\n\n- A load-mutate loop followed by one `SaveChanges[Async]` is not `SaveChanges` in 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.\n- Missing `HasIndex` calls 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.\n- Missing `AsNoTracking` is actionable only on proven read-only entity results. Scalar-only projections have nothing to track, but an entity inside a DTO\u002Frecord is still tracked by default.\n- If every reviewed pattern is sound, say that no actionable changes are needed rather than manufacturing a finding.\n\n## Capture SQL and query counts\n\nUse supplied logs and plans first. For an executable investigation, enable command logging to verify query shape and count before and after a change:\n\n```csharp\noptionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);\n\u002F\u002F or set \"Microsoft.EntityFrameworkCore.Database.Command\": \"Information\" in appsettings.json\n```\n\nTag 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.\n\n## Fixes\n\n### Trace materialization and result bounds\n\nMaterialization inside a helper is still an execution boundary. A list or array has already loaded rows; later reductions run in memory. An `IEnumerable\u003CT>` can instead hide a deferred EF query: its `Enumerable` operators process rows locally, and each enumeration may execute the database query again. Trace implementation and static types, not just method names. Keep translatable filters, projections, and aggregates on `IQueryable\u003CT>` until execution:\n\n```csharp\n\u002F\u002F Loads rows, then filters in memory.\nvar candidates = await repository.LoadCandidatesAsync(cancellationToken);\nreturn candidates.Where(o => o.CreatedAt \u003C cutoff).ToList();\n\n\u002F\u002F Composes and filters in SQL.\nreturn await repository.QueryCandidates()\n    .Where(o => o.CreatedAt \u003C cutoff)\n    .ToListAsync(cancellationToken);\n```\n\nUse `AnyAsync` for boolean existence, but preserve `CountAsync` when the numeric total is required. Combine repeated full-sequence summary calculations into server-side aggregates rather than caching an unbounded list or parallelizing queries on one context.\n\nSeparately review result cardinality. Page or cap interactive results; for complete exports, reduce buffering with streaming\u002Fchunks without truncating the contract.\n\n### Keep predicates compatible with indexes\n\nFunctions\u002Farithmetic on a column, or unanchored substring matching, commonly prevent a seek on an ordinary column index. Prefer a bare-column comparison, often a half-open range. Do not assert a full-table scan from LINQ alone: provider translations, computed\u002Fexpression indexes, and other predicates can change the plan.\n\n```csharp\n\u002F\u002F Computes a year expression instead of comparing the indexed date.\ndb.Logs.Where(l => l.CreatedAt.Year == year);\n\n\u002F\u002F Range compatible with an ordinary date index.\nvar start = new DateTime(year, 1, 1);\ndb.Logs.Where(l => l.CreatedAt >= start && l.CreatedAt \u003C start.AddYears(1));\n```\n\nThe same rule covers several common shapes:\n\n- **Case-insensitive text** — use an existing indexed normalized\u002Fcomputed value or a compatible column collation instead of wrapping the column. Query-specific collation changes can also defeat an index with a different collation. Preserve normalization and comparison semantics. `StringComparison` overloads are generally not translated by relational providers; current EF Core throws for an untranslatable predicate rather than silently filtering locally.\n- **Computed expressions** — compare against the precomputed constant, not `column * k > x`.\n- **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 may not translate. Current EF Core reports a translation failure rather than silently evaluating an untranslatable predicate on the client. Filter on the typed column with a real comparison or range instead.\n- **Substring search** — `name.Contains(term)` is generally not seekable with an ordinary B-tree index; prefix matching may be. Neither prefix matching nor token-based full-text search is a drop-in replacement for arbitrary substring matching. Preserve the required search mode or explicitly disclose the change; consider a provider-appropriate substring index\u002Fsearch design.\n\n**Verify:** when runtime validation is requested, inspect the resulting predicate and plan. An additional ordinary index does not by itself repair an incompatible expression.\n\n### Compile hot, frequently-executed queries\n\nEF Core already caches translation for matching query shapes. On a very hot, otherwise minimal query, expression processing and cache lookup can still matter. `EF.CompileQuery` \u002F `EF.CompileAsyncQuery` reuse a delegate that bypasses that lookup; they do not make database I\u002FO cheaper:\n\n```csharp\nprivate static readonly Func\u003CAppDbContext, int, ProductListItem> GetProduct =\n    EF.CompileQuery((AppDbContext db, int id) =>\n        db.Products.Where(p => p.Id == id)\n                   .Select(p => new ProductListItem(p.Id, p.Name, p.Price))\n                   .First());\n\npublic ProductListItem Lookup(AppDbContext db, int id) => GetProduct(db, id);\n```\n\nThe 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.\n\n**Verify:** the hot loop's mean time drops with identical results.\n\n### Control SQL parameterization and database plan reuse\n\nDistinguish EF's query-translation cache from the database's execution-plan cache. Captured LINQ values normally become SQL parameters, while fixed literals remain constants. Parameters keep SQL text stable across values and usually promote database plan reuse; literals expose specific values to the optimizer and can improve selectivity estimates, but many distinct literal values can fragment the server plan cache. Keep the defaults unless workload evidence supports an override:\n\n| Override | SQL effect | Performance decision |\n|----------|------------|----------------------|\n| `EF.Parameter(value)` (EF Core 9+) | Forces a parameter, including for a literal | Use when reusable SQL across values matters; already captured arguments usually need no override |\n| `EF.Constant(value)` (EF Core 8.0.2+) | Forces an inline constant, including for a captured value | Reserve for evidenced value-specific plan benefits that outweigh extra SQL variants |\n\n```csharp\ndb.Orders.Where(order => order.Status == EF.Parameter(\"Pending\"));\ndb.Orders.Where(order => order.CustomerId == EF.Constant(customerId));\n```\n\nThe first query parameterizes a fixed status; the second specializes SQL for each customer ID. Neither is inherently faster. Do not parameterize every structural literal, or inline high-cardinality request values without evidence. Provider behavior, parameter-sensitive plans, data skew, and collection translations affect the tradeoff.\n\nIn EF Core 9, these overrides are processed later than query-shape caching: `EF.Constant` can reuse EF's translation while still generating different SQL literals. It is not equivalent to embedding each request value with `Expression.Constant` in a dynamic tree. Compiled delegates do not fix server plan-cache fragmentation; EF Core 9 also does not support these overrides inside `EF.CompileQuery` \u002F `EF.CompileAsyncQuery`.\n\n**Verify:** compare generated SQL, server compilation\u002Fplan reuse, estimates, and representative latency when execution is available. A source review can identify the override and likely tradeoff, not prove a faster plan.\n\n### Stabilize dynamically constructed query shapes\n\nFollow request values into expression builders. `Expression.Constant(requestValue)` inside a comparison can produce a new EF cache entry and different SQL for each value. Represent changing values through correctly typed captured-value expressions instead:\n\n```csharp\nExpression\u003CFunc\u003Cstring>> valueAccess = () => filterValue;\nvar comparison = Expression.Equal(propertyExpression, valueAccess.Body);\n```\n\nCreating the entity's `ParameterExpression` does not parameterize its comparison values. Ordinary captured LINQ arguments are already parameterizable; fixed structural constants are not automatically defects. Preserve null\u002Fconversion semantics, and canonicalize equivalent filter order only when it is safe. Making the builder static, caching a delegate per value, or compiling every new dynamic expression does not stabilize the shape. Report potential compilation\u002Fcache churn, not a proven unbounded leak.\n\n### Choose tracking for the actual result graph\n\n| Result and consumer | Decision |\n|---------------------|----------|\n| Scalar\u002Fvalue-only projection | No entity tracking to remove; do not add `AsNoTracking` as a finding |\n| Entity or entity-valued DTO used for later edits | Preserve tracking and its identity semantics |\n| Read-only entity graph | Consider no tracking; narrow the projection first if full entities are unnecessary |\n| Read-only graph with heavily shared entities or reference-identity consumers | Consider `AsNoTrackingWithIdentityResolution`, or key-based DTO processing |\n\nPlain `AsNoTracking` does **not** resolve repeated keys to one object. Identity-resolution mode uses a query-local map without attaching results to the context; it costs bookkeeping and does not reduce joined SQL payload or deduplicate across separate queries.\n\nFor filtered Includes, inspect earlier\u002Flater loads on the same tracking context. Navigation fixup can add already tracked children that fail the Include predicate; the filtered navigation is also marked loaded. Use a detached projection with its own child filter, an appropriate no-tracking read, or a fresh read context when the subset matters. Do not clear a write tracker with pending work just to clean up a read.\n\n### Remove N+1 and avoid lazy loading\n\nThe 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`:\n\n```csharp\nvar summaries = await db.Orders\n    .Select(o => new OrderSummary(o.Id, o.Items.Count, o.Items.Sum(i => i.Price)))\n    .ToListAsync();\n```\n\nPrefer projection or `Include` over lazy loading: lazy loading is a leading cause of N+1 and forces synchronous I\u002FO. In server apps, don't enable `Microsoft.EntityFrameworkCore.Proxies` or mark navigations `virtual` for lazy loading.\n\n**Verify:** a fixed, small query count regardless of row count.\n\n### Separate join multiplication from wide-row duplication\n\nSibling collection Includes can multiply each other's rows; a nested collection chain is not the same cross-product, and references do not count as additional collections. Even one collection can repeat a wide parent blob\u002Ftext column many times. Prefer a narrow projection when the consumer does not need that column or graph. Otherwise consider `AsSplitQuery` or targeted loading:\n\n```csharp\ndb.Blogs.Include(b => b.Posts).Include(b => b.Contributors).AsSplitQuery();\n```\n\nSplitting adds statements\u002Fround-trips and can buffer results. Preserve deliberate `AsSingleQuery` and consistency requirements; stable multi-statement reads may need an appropriate snapshot\u002Fserializable transaction. Paged results need unique ordering (especially split pagination before EF Core 10); ordering is not what establishes entity identity. Do not prescribe splitting merely by counting Includes.\n\n**Verify:** lower payload\u002Frow duplication outweighs extra round-trips with the required consistency.\n\n### Filter and paginate; prefer keyset over offset\n\nConstrain large result sets with `Where`, and page with **keyset (seek)** pagination rather than `Skip`\u002F`Take`, which still scans and discards the skipped rows on deep pages:\n\n```csharp\ndb.Orders.Where(o => o.Id > lastSeenId).OrderBy(o => o.Id).Take(pageSize);\n```\n\nOrder by a unique, stable key with suitable index coverage. A descending `(CreatedAt, Id)` cursor requires `CreatedAt \u003C lastDate || (CreatedAt == lastDate && Id \u003C lastId)`, not independent bounds on both fields. Include every ordering key with its direction; IDs need not follow business timestamps.\n\nTrace ordering through query helpers and execution boundaries:\n\n- A second `OrderBy`\u002F`OrderByDescending` on an `IQueryable` replaces the earlier primary ordering; use `ThenBy` for a secondary key.\n- `OrderBy(...).Skip(...).Take(...).AsEnumerable().OrderBy(...)` first chooses a stable database window and then reorders only that bounded window in memory. That can be intentional and is not an unordered page.\n- `Skip`\u002F`Take` without a stable unique order is nondeterministic. Deep offset paging is a separate scaling concern, and keyset pagination is not behavior-preserving for random page-number access.\n- Even fully ordered offset pages can shift under concurrent inserts\u002Fdeletes; adding an order fixes nondeterminism, not cross-request snapshot consistency.\n\n**Verify:** page latency stays roughly constant from early to deep pages.\n\n### Add missing indexes\n\nAudit workload-specific coverage separately from moving filters into SQL. Inspect applied model configurations and conventions. Derive each dependent FK's ordered properties from `HasForeignKey`; EF normally supplies an index on that tuple unless an existing index\u002Fkey covers the ordered prefix and required uniqueness, or the convention was removed. Do not count only `HasIndex` calls or confuse a principal key with the dependent table's coverage. Status, timestamps, and other non-key columns may need explicit coverage. Recommend evidenced gaps for hot queries, not generic indexes in every review.\n\nIf EF Core owns the schema, add the index in the model and migrate:\n\n```csharp\nmodelBuilder.Entity\u003COrder>()\n    .HasIndex(o => new { o.CustomerId, o.CreatedAt }); \u002F\u002F equality column first, then range\u002Fsort\n```\n\nThen 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.\n\nMatch equality columns, then range\u002Fsort keys. An unconstrained intermediate key can block the desired range\u002Forder even if an earlier equality column is covered. When all initial keys use equality, more than one order may work; do not condemn a reversed composite index from relationship metadata alone. A FK index can cover the relationship but not a different date-ordered workload. Consider an additional workload index rather than replacing one that supports another path. Model code proves intended metadata, not current physical indexes; weigh write cost and provider-specific coverage.\n\n**Verify:** the plan uses a seek\u002Findex instead of a scan.\n\n### Trace persistence through repositories\n\nA service loop can hide `SaveChanges` behind a repository, audit journal, or progress hook. One final unit-of-work commit does not undo earlier writes; establish whether an enclosing transaction exists before claiming per-item commits. A save can itself require multiple SQL batches.\n\nStage bounded batches and save together when the contract permits. Preserve audit\u002Foutbox records, generated keys, relationship fixup, ordering, concurrency, and domain events. Capture IDs from the input-ordered entity references after saving; do not assume numerical ID allocation order.\n\nFor retried feeds, reason about what already committed and what the caller can replay. Preserve or design durable row\u002Ffeed identity with uniqueness and replay handling, or acknowledged checkpoints. Chunking alone is not idempotency, and an unprotected existence-check-then-insert is not race-safe.\n\n### Bound change detection in growing imports\n\nSuccessfully saved entities remain tracked. With automatic detection enabled, `ChangeTracker.Entries\u003CT>()`, `HasChanges`, and `SaveChanges` inspect tracked state; filtering entries by type does not limit the preceding scan. Repeated per-row inspection of a growing graph can create superlinear CPU work even when saves are chunked.\n\nUse import-owned progress counters instead of repeated tracker enumeration, and rotate a context or clear completed work only when that context is owned by the batch. Preserve pending changes and references. EF Core `Add` and `AddRange` do **not** automatically call `DetectChanges`; replacing one with the other is not a detection fix. Suppress automatic detection only for a demonstrated redundant scan, restore its previous setting in `finally`, and explicitly detect mutations when required before persistence\u002Fauditing.\n\n### Set-based bulk updates and deletes\n\nFor demonstrably large, simple updates\u002Fdeletes that need no per-entity processing, consider `ExecuteUpdateAsync`\u002F`ExecuteDeleteAsync` (EF Core 7+ and a supporting provider). They execute immediately without materialization:\n\n```csharp\nawait db.Products.Where(p => p.LastSoldDate \u003C cutoff)\n    .ExecuteUpdateAsync(s => s.SetProperty(p => p.IsActive, false));\n```\n\nCheck the entire write workflow:\n\n- Immediate writes do not update loaded entity values or snapshots. Later mutations of the same properties can overwrite the SQL change **even in one sequential request**. Use one coherent tracked save or an explicitly synchronized\u002Funtracked set-based path; a transaction alone does not refresh tracked state.\n- Configured concurrency tokens are not automatically checked by these APIs. Preserve token predicates, token updates, and affected-row handling when optimistic concurrency is required.\n- Each call executes separately; a later `SaveChanges` neither batches nor makes them atomic with audit\u002Foutbox writes. Use one save unit or an explicit shared transaction where required.\n- Preserve client-side cascades and SaveChanges-based hooks. Command interceptors are different and can still observe the SQL. Do not bypass domain behavior merely to reduce query count.\n\n**Verify:** a single `UPDATE`\u002F`DELETE` with a `WHERE` and no preceding `SELECT`.\n\n### Keep DbContext operations non-overlapping\n\nEF Core does not support overlapping operations on one `DbContext`, including through distinct repository objects constructed with that context. Starting both calls before awaiting either is enough; `Task.WhenAll` does not make sharing safe. Await sequentially, or create\u002Fdispose one independent context per concurrent operation. Separate factory-created contexts are safe to overlap. A static or singleton-held context also creates lifetime\u002Fthread-safety hazards.\n\n## Common Pitfalls\n\n| Pitfall | Fix |\n|---------|-----|\n| Function-wrapped predicate incompatible with an ordinary index | Use a range or an existing indexed normalized\u002Fcomputed value |\n| Fixing query composition but ignoring workload index coverage | Match the actual equality\u002Frange\u002Forder prefix, including convention-created indexes |\n| Compiling a query that runs only occasionally | Compile only genuinely hot, high-frequency query shapes |\n| Confusing EF translation reuse with database plan reuse | Inspect SQL parameter\u002Fliteral choices and justify overrides with workload evidence |\n| DTO contains entities but is assumed untracked | Inspect the materialized graph, not the outer return type |\n| Bulk write followed by tracked arithmetic on stale values | Unify writes and preserve concurrency\u002Fatomicity; do not just add a transaction |\n| Repeated enumeration of a repository's deferred `IEnumerable` | Compose database aggregates before crossing to local operators |\n\n## References\n\n- [Efficient querying — EF Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fperformance\u002Fefficient-querying)\n- [Compiled queries — EF Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fperformance\u002Fadvanced-performance-topics#compiled-queries)\n- [Force or prevent query parameterization — EF Core 9](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fwhat-is-new\u002Fef-core-9.0\u002Fwhatsnew#force-or-prevent-query-parameterization)\n- [Parameterization overrides inside compiled queries — EF Core 9](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fwhat-is-new\u002Fef-core-9.0\u002Fbreaking-changes)\n- [Efficient updating (ExecuteUpdate\u002FExecuteDelete) — EF Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fperformance\u002Fefficient-updating)\n- [Single vs. split queries](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fquerying\u002Fsingle-split-queries)\n- [Pagination](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fquerying\u002Fpagination)\n- [Indexes](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fmodeling\u002Findexes)\n","# Optimizing EF Core Queries\n\nDiagnose 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.\n\n## When to Use\n\n- EF Core queries are slow or emit far more SQL statements than expected\n- The same query repeats once per row (N+1 \u002F lazy loading)\n- Multiple collection `Include`s blow up or duplicate rows\n- Deep pages slow down as `Skip` grows, or bulk updates load rows just to modify them\n- A filtered\u002Fsorted query scans **even though the column is indexed**, or a filtered\u002Fsorted column has no supporting index\n- A hot, frequently-executed query pays EF Core's LINQ-translation cost on every call\n\n## When Not to Use\n\n- **The code uses Dapper or raw ADO.NET, not EF Core.** Answer the SQL\u002Findexing\u002Fquery-plan question directly; do not introduce a `DbContext` or recommend `AsNoTracking`, `Include`, `AsSplitQuery`, or other EF Core APIs.\n\n## Source review workflow\n\n1. 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.\n2. Trace each query to execution or enumeration. Check whether operators bind to `Queryable` or `Enumerable`, including inside helpers; an `IEnumerable` can remain a deferred database sequence.\n3. Count database operations and actual transaction boundaries along the calling path, including immediate writes and repeated enumeration. Also track which operations share the same `DbContext` instance\n4. For every execution path, independently inspect predicates, expression construction, projection contents, result bounds, ordering, Includes, tracking, SQL parameterization, and model-building code.\n5. Preserve the contract: result membership and order, random-page access, generated keys, retries, transaction and partial-failure behavior, concurrency handling, and domain\u002Finterceptor side effects.\n6. 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.\n\nFor a source-only request, recommend runtime validation as a next step.\n\nFor raw SQL, prefer EF Core's interpolated overloads (`FromSql` \u002F `FromSqlInterpolated` and `ExecuteSql[Async]`) so values are sent as parameters.\n\n## Gate source-only findings on evidence\n\nWhen the user requests a source-only review, distinguish a demonstrated defect from an optimization that still needs workload or deployment evidence:\n\n- A load-mutate loop followed by one `SaveChanges[Async]` is not `SaveChanges` in 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.\n- Missing `HasIndex` calls 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.\n- Missing `AsNoTracking` is actionable only on proven read-only entity results. Scalar-only projections have nothing to track, but an entity inside a DTO\u002Frecord is still tracked by default.\n- If every reviewed pattern is sound, say that no actionable changes are needed rather than manufacturing a finding.\n\n## Capture SQL and query counts\n\nUse supplied logs and plans first. For an executable investigation, enable command logging to verify query shape and count before and after a change:\n\n```csharp\noptionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);\n\u002F\u002F or set \"Microsoft.EntityFrameworkCore.Database.Command\": \"Information\" in appsettings.json\n```\n\nTag 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.\n\n## Fixes\n\n### Trace materialization and result bounds\n\nMaterialization inside a helper is still an execution boundary. A list or array has already loaded rows; later reductions run in memory. An `IEnumerable\u003CT>` can instead hide a deferred EF query: its `Enumerable` operators process rows locally, and each enumeration may execute the database query again. Trace implementation and static types, not just method names. Keep translatable filters, projections, and aggregates on `IQueryable\u003CT>` until execution:\n\n```csharp\n\u002F\u002F Loads rows, then filters in memory.\nvar candidates = await repository.LoadCandidatesAsync(cancellationToken);\nreturn candidates.Where(o => o.CreatedAt \u003C cutoff).ToList();\n\n\u002F\u002F Composes and filters in SQL.\nreturn await repository.QueryCandidates()\n    .Where(o => o.CreatedAt \u003C cutoff)\n    .ToListAsync(cancellationToken);\n```\n\nUse `AnyAsync` for boolean existence, but preserve `CountAsync` when the numeric total is required. Combine repeated full-sequence summary calculations into server-side aggregates rather than caching an unbounded list or parallelizing queries on one context.\n\nSeparately review result cardinality. Page or cap interactive results; for complete exports, reduce buffering with streaming\u002Fchunks without truncating the contract.\n\n### Keep predicates compatible with indexes\n\nFunctions\u002Farithmetic on a column, or unanchored substring matching, commonly prevent a seek on an ordinary column index. Prefer a bare-column comparison, often a half-open range. Do not assert a full-table scan from LINQ alone: provider translations, computed\u002Fexpression indexes, and other predicates can change the plan.\n\n```csharp\n\u002F\u002F Computes a year expression instead of comparing the indexed date.\ndb.Logs.Where(l => l.CreatedAt.Year == year);\n\n\u002F\u002F Range compatible with an ordinary date index.\nvar start = new DateTime(year, 1, 1);\ndb.Logs.Where(l => l.CreatedAt >= start && l.CreatedAt \u003C start.AddYears(1));\n```\n\nThe same rule covers several common shapes:\n\n- **Case-insensitive text** — use an existing indexed normalized\u002Fcomputed value or a compatible column collation instead of wrapping the column. Query-specific collation changes can also defeat an index with a different collation. Preserve normalization and comparison semantics. `StringComparison` overloads are generally not translated by relational providers; current EF Core throws for an untranslatable predicate rather than silently filtering locally.\n- **Computed expressions** — compare against the precomputed constant, not `column * k > x`.\n- **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 may not translate. Current EF Core reports a translation failure rather than silently evaluating an untranslatable predicate on the client. Filter on the typed column with a real comparison or range instead.\n- **Substring search** — `name.Contains(term)` is generally not seekable with an ordinary B-tree index; prefix matching may be. Neither prefix matching nor token-based full-text search is a drop-in replacement for arbitrary substring matching. Preserve the required search mode or explicitly disclose the change; consider a provider-appropriate substring index\u002Fsearch design.\n\n**Verify:** when runtime validation is requested, inspect the resulting predicate and plan. An additional ordinary index does not by itself repair an incompatible expression.\n\n### Compile hot, frequently-executed queries\n\nEF Core already caches translation for matching query shapes. On a very hot, otherwise minimal query, expression processing and cache lookup can still matter. `EF.CompileQuery` \u002F `EF.CompileAsyncQuery` reuse a delegate that bypasses that lookup; they do not make database I\u002FO cheaper:\n\n```csharp\nprivate static readonly Func\u003CAppDbContext, int, ProductListItem> GetProduct =\n    EF.CompileQuery((AppDbContext db, int id) =>\n        db.Products.Where(p => p.Id == id)\n                   .Select(p => new ProductListItem(p.Id, p.Name, p.Price))\n                   .First());\n\npublic ProductListItem Lookup(AppDbContext db, int id) => GetProduct(db, id);\n```\n\nThe 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.\n\n**Verify:** the hot loop's mean time drops with identical results.\n\n### Control SQL parameterization and database plan reuse\n\nDistinguish EF's query-translation cache from the database's execution-plan cache. Captured LINQ values normally become SQL parameters, while fixed literals remain constants. Parameters keep SQL text stable across values and usually promote database plan reuse; literals expose specific values to the optimizer and can improve selectivity estimates, but many distinct literal values can fragment the server plan cache. Keep the defaults unless workload evidence supports an override:\n\n| Override | SQL effect | Performance decision |\n|----------|------------|----------------------|\n| `EF.Parameter(value)` (EF Core 9+) | Forces a parameter, including for a literal | Use when reusable SQL across values matters; already captured arguments usually need no override |\n| `EF.Constant(value)` (EF Core 8.0.2+) | Forces an inline constant, including for a captured value | Reserve for evidenced value-specific plan benefits that outweigh extra SQL variants |\n\n```csharp\ndb.Orders.Where(order => order.Status == EF.Parameter(\"Pending\"));\ndb.Orders.Where(order => order.CustomerId == EF.Constant(customerId));\n```\n\nThe first query parameterizes a fixed status; the second specializes SQL for each customer ID. Neither is inherently faster. Do not parameterize every structural literal, or inline high-cardinality request values without evidence. Provider behavior, parameter-sensitive plans, data skew, and collection translations affect the tradeoff.\n\nIn EF Core 9, these overrides are processed later than query-shape caching: `EF.Constant` can reuse EF's translation while still generating different SQL literals. It is not equivalent to embedding each request value with `Expression.Constant` in a dynamic tree. Compiled delegates do not fix server plan-cache fragmentation; EF Core 9 also does not support these overrides inside `EF.CompileQuery` \u002F `EF.CompileAsyncQuery`.\n\n**Verify:** compare generated SQL, server compilation\u002Fplan reuse, estimates, and representative latency when execution is available. A source review can identify the override and likely tradeoff, not prove a faster plan.\n\n### Stabilize dynamically constructed query shapes\n\nFollow request values into expression builders. `Expression.Constant(requestValue)` inside a comparison can produce a new EF cache entry and different SQL for each value. Represent changing values through correctly typed captured-value expressions instead:\n\n```csharp\nExpression\u003CFunc\u003Cstring>> valueAccess = () => filterValue;\nvar comparison = Expression.Equal(propertyExpression, valueAccess.Body);\n```\n\nCreating the entity's `ParameterExpression` does not parameterize its comparison values. Ordinary captured LINQ arguments are already parameterizable; fixed structural constants are not automatically defects. Preserve null\u002Fconversion semantics, and canonicalize equivalent filter order only when it is safe. Making the builder static, caching a delegate per value, or compiling every new dynamic expression does not stabilize the shape. Report potential compilation\u002Fcache churn, not a proven unbounded leak.\n\n### Choose tracking for the actual result graph\n\n| Result and consumer | Decision |\n|---------------------|----------|\n| Scalar\u002Fvalue-only projection | No entity tracking to remove; do not add `AsNoTracking` as a finding |\n| Entity or entity-valued DTO used for later edits | Preserve tracking and its identity semantics |\n| Read-only entity graph | Consider no tracking; narrow the projection first if full entities are unnecessary |\n| Read-only graph with heavily shared entities or reference-identity consumers | Consider `AsNoTrackingWithIdentityResolution`, or key-based DTO processing |\n\nPlain `AsNoTracking` does **not** resolve repeated keys to one object. Identity-resolution mode uses a query-local map without attaching results to the context; it costs bookkeeping and does not reduce joined SQL payload or deduplicate across separate queries.\n\nFor filtered Includes, inspect earlier\u002Flater loads on the same tracking context. Navigation fixup can add already tracked children that fail the Include predicate; the filtered navigation is also marked loaded. Use a detached projection with its own child filter, an appropriate no-tracking read, or a fresh read context when the subset matters. Do not clear a write tracker with pending work just to clean up a read.\n\n### Remove N+1 and avoid lazy loading\n\nThe 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`:\n\n```csharp\nvar summaries = await db.Orders\n    .Select(o => new OrderSummary(o.Id, o.Items.Count, o.Items.Sum(i => i.Price)))\n    .ToListAsync();\n```\n\nPrefer projection or `Include` over lazy loading: lazy loading is a leading cause of N+1 and forces synchronous I\u002FO. In server apps, don't enable `Microsoft.EntityFrameworkCore.Proxies` or mark navigations `virtual` for lazy loading.\n\n**Verify:** a fixed, small query count regardless of row count.\n\n### Separate join multiplication from wide-row duplication\n\nSibling collection Includes can multiply each other's rows; a nested collection chain is not the same cross-product, and references do not count as additional collections. Even one collection can repeat a wide parent blob\u002Ftext column many times. Prefer a narrow projection when the consumer does not need that column or graph. Otherwise consider `AsSplitQuery` or targeted loading:\n\n```csharp\ndb.Blogs.Include(b => b.Posts).Include(b => b.Contributors).AsSplitQuery();\n```\n\nSplitting adds statements\u002Fround-trips and can buffer results. Preserve deliberate `AsSingleQuery` and consistency requirements; stable multi-statement reads may need an appropriate snapshot\u002Fserializable transaction. Paged results need unique ordering (especially split pagination before EF Core 10); ordering is not what establishes entity identity. Do not prescribe splitting merely by counting Includes.\n\n**Verify:** lower payload\u002Frow duplication outweighs extra round-trips with the required consistency.\n\n### Filter and paginate; prefer keyset over offset\n\nConstrain large result sets with `Where`, and page with **keyset (seek)** pagination rather than `Skip`\u002F`Take`, which still scans and discards the skipped rows on deep pages:\n\n```csharp\ndb.Orders.Where(o => o.Id > lastSeenId).OrderBy(o => o.Id).Take(pageSize);\n```\n\nOrder by a unique, stable key with suitable index coverage. A descending `(CreatedAt, Id)` cursor requires `CreatedAt \u003C lastDate || (CreatedAt == lastDate && Id \u003C lastId)`, not independent bounds on both fields. Include every ordering key with its direction; IDs need not follow business timestamps.\n\nTrace ordering through query helpers and execution boundaries:\n\n- A second `OrderBy`\u002F`OrderByDescending` on an `IQueryable` replaces the earlier primary ordering; use `ThenBy` for a secondary key.\n- `OrderBy(...).Skip(...).Take(...).AsEnumerable().OrderBy(...)` first chooses a stable database window and then reorders only that bounded window in memory. That can be intentional and is not an unordered page.\n- `Skip`\u002F`Take` without a stable unique order is nondeterministic. Deep offset paging is a separate scaling concern, and keyset pagination is not behavior-preserving for random page-number access.\n- Even fully ordered offset pages can shift under concurrent inserts\u002Fdeletes; adding an order fixes nondeterminism, not cross-request snapshot consistency.\n\n**Verify:** page latency stays roughly constant from early to deep pages.\n\n### Add missing indexes\n\nAudit workload-specific coverage separately from moving filters into SQL. Inspect applied model configurations and conventions. Derive each dependent FK's ordered properties from `HasForeignKey`; EF normally supplies an index on that tuple unless an existing index\u002Fkey covers the ordered prefix and required uniqueness, or the convention was removed. Do not count only `HasIndex` calls or confuse a principal key with the dependent table's coverage. Status, timestamps, and other non-key columns may need explicit coverage. Recommend evidenced gaps for hot queries, not generic indexes in every review.\n\nIf EF Core owns the schema, add the index in the model and migrate:\n\n```csharp\nmodelBuilder.Entity\u003COrder>()\n    .HasIndex(o => new { o.CustomerId, o.CreatedAt }); \u002F\u002F equality column first, then range\u002Fsort\n```\n\nThen 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.\n\nMatch equality columns, then range\u002Fsort keys. An unconstrained intermediate key can block the desired range\u002Forder even if an earlier equality column is covered. When all initial keys use equality, more than one order may work; do not condemn a reversed composite index from relationship metadata alone. A FK index can cover the relationship but not a different date-ordered workload. Consider an additional workload index rather than replacing one that supports another path. Model code proves intended metadata, not current physical indexes; weigh write cost and provider-specific coverage.\n\n**Verify:** the plan uses a seek\u002Findex instead of a scan.\n\n### Trace persistence through repositories\n\nA service loop can hide `SaveChanges` behind a repository, audit journal, or progress hook. One final unit-of-work commit does not undo earlier writes; establish whether an enclosing transaction exists before claiming per-item commits. A save can itself require multiple SQL batches.\n\nStage bounded batches and save together when the contract permits. Preserve audit\u002Foutbox records, generated keys, relationship fixup, ordering, concurrency, and domain events. Capture IDs from the input-ordered entity references after saving; do not assume numerical ID allocation order.\n\nFor retried feeds, reason about what already committed and what the caller can replay. Preserve or design durable row\u002Ffeed identity with uniqueness and replay handling, or acknowledged checkpoints. Chunking alone is not idempotency, and an unprotected existence-check-then-insert is not race-safe.\n\n### Bound change detection in growing imports\n\nSuccessfully saved entities remain tracked. With automatic detection enabled, `ChangeTracker.Entries\u003CT>()`, `HasChanges`, and `SaveChanges` inspect tracked state; filtering entries by type does not limit the preceding scan. Repeated per-row inspection of a growing graph can create superlinear CPU work even when saves are chunked.\n\nUse import-owned progress counters instead of repeated tracker enumeration, and rotate a context or clear completed work only when that context is owned by the batch. Preserve pending changes and references. EF Core `Add` and `AddRange` do **not** automatically call `DetectChanges`; replacing one with the other is not a detection fix. Suppress automatic detection only for a demonstrated redundant scan, restore its previous setting in `finally`, and explicitly detect mutations when required before persistence\u002Fauditing.\n\n### Set-based bulk updates and deletes\n\nFor demonstrably large, simple updates\u002Fdeletes that need no per-entity processing, consider `ExecuteUpdateAsync`\u002F`ExecuteDeleteAsync` (EF Core 7+ and a supporting provider). They execute immediately without materialization:\n\n```csharp\nawait db.Products.Where(p => p.LastSoldDate \u003C cutoff)\n    .ExecuteUpdateAsync(s => s.SetProperty(p => p.IsActive, false));\n```\n\nCheck the entire write workflow:\n\n- Immediate writes do not update loaded entity values or snapshots. Later mutations of the same properties can overwrite the SQL change **even in one sequential request**. Use one coherent tracked save or an explicitly synchronized\u002Funtracked set-based path; a transaction alone does not refresh tracked state.\n- Configured concurrency tokens are not automatically checked by these APIs. Preserve token predicates, token updates, and affected-row handling when optimistic concurrency is required.\n- Each call executes separately; a later `SaveChanges` neither batches nor makes them atomic with audit\u002Foutbox writes. Use one save unit or an explicit shared transaction where required.\n- Preserve client-side cascades and SaveChanges-based hooks. Command interceptors are different and can still observe the SQL. Do not bypass domain behavior merely to reduce query count.\n\n**Verify:** a single `UPDATE`\u002F`DELETE` with a `WHERE` and no preceding `SELECT`.\n\n### Keep DbContext operations non-overlapping\n\nEF Core does not support overlapping operations on one `DbContext`, including through distinct repository objects constructed with that context. Starting both calls before awaiting either is enough; `Task.WhenAll` does not make sharing safe. Await sequentially, or create\u002Fdispose one independent context per concurrent operation. Separate factory-created contexts are safe to overlap. A static or singleton-held context also creates lifetime\u002Fthread-safety hazards.\n\n## Common Pitfalls\n\n| Pitfall | Fix |\n|---------|-----|\n| Function-wrapped predicate incompatible with an ordinary index | Use a range or an existing indexed normalized\u002Fcomputed value |\n| Fixing query composition but ignoring workload index coverage | Match the actual equality\u002Frange\u002Forder prefix, including convention-created indexes |\n| Compiling a query that runs only occasionally | Compile only genuinely hot, high-frequency query shapes |\n| Confusing EF translation reuse with database plan reuse | Inspect SQL parameter\u002Fliteral choices and justify overrides with workload evidence |\n| DTO contains entities but is assumed untracked | Inspect the materialized graph, not the outer return type |\n| Bulk write followed by tracked arithmetic on stale values | Unify writes and preserve concurrency\u002Fatomicity; do not just add a transaction |\n| Repeated enumeration of a repository's deferred `IEnumerable` | Compose database aggregates before crossing to local operators |\n\n## References\n\n- [Efficient querying — EF Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fperformance\u002Fefficient-querying)\n- [Compiled queries — EF Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fperformance\u002Fadvanced-performance-topics#compiled-queries)\n- [Force or prevent query parameterization — EF Core 9](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fwhat-is-new\u002Fef-core-9.0\u002Fwhatsnew#force-or-prevent-query-parameterization)\n- [Parameterization overrides inside compiled queries — EF Core 9](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fwhat-is-new\u002Fef-core-9.0\u002Fbreaking-changes)\n- [Efficient updating (ExecuteUpdate\u002FExecuteDelete) — EF Core](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fperformance\u002Fefficient-updating)\n- [Single vs. split queries](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fquerying\u002Fsingle-split-queries)\n- [Pagination](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fquerying\u002Fpagination)\n- [Indexes](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fef\u002Fcore\u002Fmodeling\u002Findexes)\n",{"name":5,"license":14,"description":7},"main","ccab8dffc0ecc173838f51e4c5f0d3b51a704f41","plugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Foptimizing-ef-core-queries","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills","https:\u002F\u002Fgithub.com\u002Fdeadmade","https:\u002F\u002Fdeadmade.github.io\u002F","Blood, an Ocean of blood","2026-11-14 02:03:31",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add deadmade\u002Fdead-agent-skills --skill optimizing-ef-core-queries",{"tool":37,"command":38},"bunx","bunx skills add deadmade\u002Fdead-agent-skills --skill optimizing-ef-core-queries",{"tool":40,"command":41},"pnpm","pnpm dlx skills add deadmade\u002Fdead-agent-skills --skill optimizing-ef-core-queries","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Foptimizing-ef-core-queries\u002FSKILL.md",true,[],[46,53,62,70,77,84],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":18},"01M7CVRBFTXSTTQ7F5P6PJEFYA","rust-best-practices","Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook. Use this skill when: (1) writing new Rust code or functions, (2) reviewing or refactoring existing Rust code, (3) deciding between borrowing vs cloning or ownership patterns, (4) implementing error handling with Result types, (5) optimizing Rust code for performance, (6) writing tests or documentation for Rust projects.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Frust-skills\u002Fskills\u002Frust-best-practices\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":57,"licenseFileUrl":58,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7CVR0W7B8EGTNPSPA7FPC4Z","postgres-database-migration","Use this skill for planning, testing, and safely executing PostgreSQL schema migrations — especially when working with production data or shared databases.\n\n**Trigger when user asks to:**\n- Test a schema migration before applying it to production\n- Add, remove, or rename columns safely on a live table\n- Change a column's data type without downtime\n- Add or drop indexes, constraints, or foreign keys on large tables\n- Understand which ALTER TABLE operations lock the table\n- Roll back a failed migration\n- Plan a zero-downtime migration strategy\n- Fork a database to test a migration safely\n\nCovers: lock-level reference for every common DDL operation, safe migration patterns, fork-based testing, zero-downtime column changes, index creation, constraint addition, backfill strategies, pre\u002Fpost-migration validation, and rollback planning.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-database-migration\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-database-migration\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":57,"licenseFileUrl":66,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":18},"01M7CVQWK20ASAZN5VETZC8J99","postgres-best-practices","Best practices and guidelines for working with Postgres. Covers schema design, indexing strategies, query optimization, migrations, and common pitfalls. Use when writing SQL, designing database schemas, optimizing queries, or setting up a Postgres database.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-best-practices\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fpostgres\u002Fskills\u002Fpostgres-best-practices\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":18},"01M7CVQ5CY7AQHY7A2Y99RE6A7","writing-mstest-tests","ALWAYS USE when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":18},"01M7CVPWJZ63GB0810F0SCGZ1K","winforms-expert","Create, modify, debug, or review Windows Forms applications only when the request contains a concrete Windows Forms marker. USE FOR: WinForms, Windows Forms, System.Windows.Forms, WinForms Form or UserControl designer files (*.Designer.cs or *.Designer.vb), Visual Studio WinForms Designer, TableLayoutPanel, BindingSource, DataGridView, Control.InvokeAsync, component-tray ownership, or custom control serialization. DO NOT USE FOR: WPF or WPF XAML, including Window.InputBindings, KeyBinding, commands, or DataContext; .NET MAUI; Avalonia; or any request where none of the listed Windows Forms markers is present.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fwinforms-expert\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":18},"01M7CVPR0QFZ1HMJ6GZRBQAQ7W","vectorization","Design, implement, optimize, and review SIMD code in .NET. USE FOR: vectorizing scalar loops with TensorPrimitives, Vector64\u002F128\u002F256\u002F512, or platform hardware intrinsics; reviewing existing SIMD code, including the generic Vector type, for contract equivalence, tail handling, memory safety, portability, fallbacks, and measured performance. DO NOT USE FOR: performance work unrelated to SIMD or vectorization.","https:\u002F\u002Fgithub.com\u002Fdeadmade\u002Fdead-agent-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fopt-in\u002Fimplementation\u002Fcsharp-skills\u002Flibrary\u002Fvectorization\u002FSKILL.md",[],[]]