Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
AI

The AI Prompt That Spots N+1 Query Patterns Hiding Inside Your ORM Code

- 03.10.26 - ErcanOPAK

🤖 The Prompt That Counts Queries the Way Your Database Would

An N+1 query bug happens when code loads a list of records with one query, then loops over that list making a separate query per item to fetch related data – a pattern that runs fine with five test rows and falls over with five thousand production ones. It’s genuinely hard to spot by reading code alone, because each individual line looks completely reasonable in isolation; the problem only exists in the relationship between a loop and a lazy-loading call inside it, which is exactly the kind of cross-line pattern an AI model with the right prompt can scan for quickly across a whole file.

🔎 The Problem

You are reviewing code that uses an ORM (Entity Framework, Hibernate,
Django ORM, ActiveRecord, or similar - identify which one from context)
for N+1 query patterns. For each file I paste, look specifically for:

1. A loop (for, foreach, .map(), list comprehension) that accesses a
   navigation property, related object, or lazy-loaded collection
   INSIDE the loop body, where that access triggers a separate
   database round trip per iteration.
2. Any place a "fix" for this - like .Include()/.ThenInclude() in EF,
   select_related()/prefetch_related() in Django, or eager loading in
   ActiveRecord - is clearly missing given how the result is later used.

For each finding, show: the loop in question, which line triggers the
extra queries, roughly how many total queries it produces for N items,
and the specific eager-loading call that fixes it for this ORM. Code:

[paste your code here]

✅ Why This Prompt Works

  • Asking the model to identify the ORM first keeps the suggested fix concrete and correct – the eager-loading syntax for Entity Framework, Django, and ActiveRecord are all different, and a generic answer isn’t actionable.
  • Requesting a rough query count for N items reframes the finding in terms that matter to a reviewer – ‘1 query becomes 501 queries for 500 rows’ is far more persuasive than an abstract description of the pattern.
  • Focusing specifically on loop-plus-lazy-access keeps the review targeted, since this is a narrow, well-defined pattern an AI model can scan for reliably, unlike vaguer ‘find performance problems’ requests.

⚠️ Getting the Most Out of It

  • Include the model/entity class definitions alongside the query code when you can, since knowing which properties are lazy-loaded navigation properties versus already-loaded scalar fields is what separates a real finding from a false positive.
  • Double check any flagged loop against your actual data volumes – a loop over a collection that’s always small in practice is a much lower priority fix than one iterating over a table that grows without bound.

N+1 isn’t a bug in any single line – it’s a bug in the relationship between a loop and a query, and that’s precisely the kind of pattern easy for a person to read past and easy for a model to be asked to look for specifically.

— AI Power User

Related posts:

AI Prompt: Summarize Meeting Notes and Action Items

AI Prompt: Generate SWOT Analysis for Your Business or Project

AI Prompt: Use AI as Senior Code Reviewer for Pull Requests

Post Views: 3

Post navigation

SQL Server: Fix a Filtered Index That Gets Silently Ignored Because the Query’s WHERE Clause Doesn’t Match It Exactly
WordPress: Fix Child Theme Styles That Silently Stop Overriding the Parent Theme After a Core Update

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (938)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (624)
  • Add Constraint to SQL Table to ensure email contains @ (590)
  • Average of all values in a column that are not zero in SQL (553)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (526)
  • Find numbers with more than two decimal places in SQL (468)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (938)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com