Skip to main content

Entity Framework Core Performance Optimization

Optimize Entity Framework Core queries — fix N+1 problems, configure eager loading, query splitting, projection, and fine-tune change tracking with benchmarks.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Optimize Entity Framework Core performance in my .NET 8 application. The database is SQL Server with 25 entities. 1) N+1 detection: show how to identify N+1 queries using EF Core logging with EnableSensitiveDataLogging in development and fix them with Include(), ThenInclude(), and AsSplitQuery() — demonstrate with loading orders with their items and product details for a customer list page. 2) Query optimization: rewrite dashboard summary loading all order entities to calculate aggregates in memory using projection (Select) to avoid loading unnecessary columns, and use compiled queries for product lookup by SKU, user authentication check. 3) Change tracking: configure NoTracking for read-only queries, explain when to use AsNoTrackingWithIdentityResolution(), and show the performance impact. 4) Bulk operations: replace SaveChanges() loops with EFCore.BulkExtensions for importing 10,000 products and updating prices in batch — show before/after benchmarks. 5) Connection management: configure connection pooling, command timeout, and retry policies for transient failures. 6) Indexing: analyze the EF model and suggest database indexes for filtering orders by status and date, searching products by SKU — generate migration with proper index definitions. 7) Lazy loading vs explicit loading: explain when each is appropriate and configure lazy loading proxies safely. 8) Benchmarking: set up BenchmarkDotNet tests comparing the old vs optimized queries.

What this prompt does

This prompt drives a focused Entity Framework Core performance pass on a [dotnet_version] application backed by [database] with [entity_count] entities. It walks through N+1 detection using [logging_approach], query optimization with projection and compiled queries for [frequent_queries], change-tracking configuration, bulk operations via [bulk_library], connection management, indexing for [index_scenarios], and lazy-versus-explicit loading. Each step targets a concrete scenario like [n1_scenario] or [slow_query] rather than abstract advice.

The structure works because almost every EF Core slowdown traces back to N+1 queries or change tracking left on for read-only paths, so the prompt instruments those first. It insists on BenchmarkDotNet before-and-after numbers, because "it feels faster" is not a result you can defend. Fixing [n1_scenario] with Include(), ThenInclude(), and AsSplitQuery(), then projecting [slow_query] with Select to avoid loading unused columns, is where most of the real wins come from.

When to use it

  • A page or endpoint is slow and you suspect N+1 queries behind [n1_scenario]
  • A query like [slow_query] loads far more data than it needs and you want to project it down
  • You are running read-only queries that don't need change tracking and want the performance back
  • You need to replace SaveChanges() loops with [bulk_library] for [bulk_operations]
  • You want indexes suggested and a migration generated for [index_scenarios]
  • You need defensible before-and-after benchmarks rather than subjective "feels faster" claims

Example output

Expect a remediation walkthrough: how to surface N+1 queries through logging, refactored queries using Include(), ThenInclude(), AsSplitQuery(), and projection, AsNoTracking guidance with performance notes, bulk-operation code with before/after benchmarks, connection-pooling and retry configuration, suggested indexes with a generated migration, lazy-versus-explicit loading guidance, and BenchmarkDotNet tests comparing old and optimized versions.

Pro tips

  • Describe [n1_scenario] precisely — "orders with items and product details for a customer list" tells the model exactly which Include and split-query strategy to apply
  • Reach for AsSplitQuery() when a single Include-heavy query produces a Cartesian explosion, but benchmark it, since extra round-trips can sometimes be slower
  • Add AsNoTracking to read-only paths first; it is the lowest-risk change with a real payoff, especially on large result sets
  • Choose [bulk_library] deliberately — third-party bulk extensions bypass change tracking, so they are fast but skip EF's safety nets
  • Always run the BenchmarkDotNet step; the model can suggest optimizations, but only measured numbers tell you which ones actually helped your workload
  • Verify suggested indexes against your real query plans before adding them all, since every index adds write overhead
  • Use compiled queries for [frequent_queries] that run constantly, since caching the query plan removes repeated expression-tree compilation on hot paths
  • Prefer AsNoTrackingWithIdentityResolution() over plain AsNoTracking() when a read-only query returns the same entity multiple times and you need reference equality
  • Profile against production-like data volumes, not a tiny dev database, because an N+1 that looks fine on ten rows is what tanks the page on ten thousand

Frequently Asked Questions

How does this prompt help me find N+1 queries?
It shows how to surface them using your `[logging_approach]`, such as EF Core logging with sensitive data logging enabled in development, then demonstrates the fix on your `[n1_scenario]` with `Include()`, `ThenInclude()`, and `AsSplitQuery()`. Reviewing the generated SQL is how you confirm the N+1 pattern is actually gone.
When should I use AsSplitQuery versus a single query?
Use `AsSplitQuery()` when an `Include`-heavy query joins multiple collections and produces a Cartesian explosion of duplicated rows. It trades one large query for several smaller round-trips. The prompt suggests it, but benchmark both, because for smaller result sets the extra round-trips can occasionally be slower than a single join.
Does it provide actual benchmarks or just suggestions?
It sets up BenchmarkDotNet tests comparing your original and optimized queries, so you get measured numbers rather than guesses. This is deliberate — the prompt treats before-and-after benchmarks as the standard of proof, since perceived speed improvements are unreliable and can mask regressions on other code paths.
Are the suggested indexes safe to add directly?
Treat them as candidates. The prompt analyzes your `[index_scenarios]` and generates a migration, but every index adds write and storage overhead. Verify each one against your actual query plans and write patterns before applying them all, because an index that speeds one query can slow inserts and updates elsewhere.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in C# & .NET Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by OpenAI

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support