SkillPilotAI

Querying and N+1

EF Core turns LINQ into SQL, and the SQL it sends decides how fast your app is. This note shows how to see that SQL, how to spot and fix the N+1 problem, and how to keep read queries lean with projection, AsNoTracking and pagination.

54.1 The problem: a query inside a loop

  • The code loads all customers, then calls CountAsync for every customer inside the loop.
  • The output is correct, but the SQL log shows a separate COUNT query per customer: 5 queries for 4 customers.
C#
var customers = await db.Customers.ToListAsync(); foreach (var c in customers){    var count = await db.Orders        .CountAsync(o => o.CustomerId == c.Id);    Console.WriteLine($"{c.Name}: {count} orders");}
Output
$ dotnet run -- nplus1      SELECT "c"."Id", "c"."City", "c"."Name"      FROM "Customers" AS "c"      SELECT COUNT(*)      FROM "Orders" AS "o"      WHERE "o"."CustomerId" = @c_IdAsha: 2 orders      SELECT COUNT(*) ...Ravi: 1 orders      SELECT COUNT(*) ...Meera: 3 orders      SELECT COUNT(*) ...Kabir: 0 orders$ dotnet run -- nplus1 | grep -c "Executed DbCommand"5

54.2 Why it is slow: the N+1 problem

  • Every await is a separate database round trip.
  • A query inside a loop = as many queries as rows: 500 customers -> 501 queries, and the network time adds up.
  • Name: 1 query for the list + N queries for the rows.
The N+1 problem
  1. 1.1 query: all customers

  2. 2.N queries: a COUNT per customer

  3. 3.500 customers -> 501 round trips

Query inside a loop = N+1

54.3 Seeing the SQL: LogTo and ToQueryString

  • LogTo in OnConfiguring writes logs to the console; filter to DbLoggerCategory.Database.Command so only SQL shows.
  • Each log line has the command time, the parameters and the full SQL.
  • A LINQ query is just an IQueryable until it runs (deferred execution).
  • ToQueryString shows the SQL without running it: Where -> WHERE, OrderBy -> ORDER BY, city -> a parameter.
C#
protected override void OnConfiguring(    DbContextOptionsBuilder options) => options    .UseSqlite("Data Source=shop.db")    .LogTo(Console.WriteLine,        [DbLoggerCategory.Database.Command.Name],        LogLevel.Information);
C#
var city = "Pune";var query = db.Customers    .Where(c => c.City == city)    .OrderBy(c => c.Name); Console.WriteLine(query.ToQueryString()); var pune = await query.ToListAsync();Console.WriteLine($"Found: {pune.Count}");
Output
$ dotnet run -- sql.param set @city 'Pune' SELECT "c"."Id", "c"."City", "c"."Name"FROM "Customers" AS "c"WHERE "c"."City" = @cityORDER BY "c"."Name"...Found: 2
From LINQ to objects
  1. 1.LINQ query: IQueryable = expression tree

  2. 2.Translate: provider -> SQL

  3. 3.Execute: database -> rows

  4. 4.Materialize: rows -> objects (+ tracking)

The query runs on ToListAsync / foreach

54.4 Fix 1: Include

  • Include(c => c.Orders) loads each customer's orders in the same query.
  • c.Orders is already in memory inside the loop, so no query runs there.
  • One SQL with a LEFT JOIN: command count = 1.
C#
var customers = await db.Customers    .Include(c => c.Orders)    .ToListAsync(); foreach (var c in customers)    Console.WriteLine(        $"{c.Name}: {c.Orders.Count} orders");
Output
$ dotnet run -- include      SELECT "c"."Id", "c"."City", "c"."Name", "o"."Id", "o"."Amount", "o"."CustomerId"      FROM "Customers" AS "c"      LEFT JOIN "Orders" AS "o" ON "c"."Id" = "o"."CustomerId"      ORDER BY "c"."Id"Asha: 2 ordersRavi: 1 ordersMeera: 3 ordersKabir: 0 orders$ dotnet run -- include | grep -c "Executed DbCommand"1

54.5 Fix 2: Select projection

  • Include loads full entities; here we only need name, order count and total.
  • Select builds a CustomerSummary record directly; Count and Sum are computed inside SQL as subqueries.
  • Result: one query and less data over the wire.
C#
var rows = await db.Customers    .Select(c => new CustomerSummary(        c.Name,        c.Orders.Count,        c.Orders.Sum(o => o.Amount)))    .ToListAsync(); foreach (var r in rows)    Console.WriteLine(r);
Output
$ dotnet run -- select      SELECT "c"."Name", (          SELECT COUNT(*)          FROM "Orders" AS "o"          WHERE "c"."Id" = "o"."CustomerId"), (          SELECT COALESCE(SUM("o0"."Amount"), 0)          FROM "Orders" AS "o0"          WHERE "c"."Id" = "o0"."CustomerId")      FROM "Customers" AS "c"CustomerSummary { Name = Asha, OrderCount = 2, TotalSpent = 1749 }CustomerSummary { Name = Ravi, OrderCount = 1, TotalSpent = 2999 }CustomerSummary { Name = Meera, OrderCount = 3, TotalSpent = 2649 }CustomerSummary { Name = Kabir, OrderCount = 0, TotalSpent = 0 }

54.6 AsNoTracking: read-only queries

  • By default EF keeps a snapshot of every loaded entity in the ChangeTracker, so SaveChanges can detect changes.
  • AsNoTracking: same SQL, but nothing is tracked (Tracked: 0). Saves memory and time in read-only endpoints.
C#
var tracked = await db.Customers    .ToListAsync();var count = db.ChangeTracker.Entries().Count();Console.WriteLine($"Tracked: {count}"); db.ChangeTracker.Clear(); var readOnly = await db.Customers    .AsNoTracking()    .ToListAsync();count = db.ChangeTracker.Entries().Count();Console.WriteLine($"Tracked: {count}");
Output
$ dotnet run -- tracking | grep TrackedTracked: 4Tracked: 0

54.7 Pagination: Skip + Take

  • A list endpoint should never return the whole table.
  • Skip((page - 1) * pageSize) then Take(pageSize); page 3, size 2 -> orders 5 and 6.
  • OrderBy is required: without a fixed order pages can repeat or miss rows.
  • In SQL it becomes LIMIT and OFFSET.
C#
int page = 3, pageSize = 2; var items = await db.Orders    .AsNoTracking()    .OrderBy(o => o.Id)    .Skip((page - 1) * pageSize)    .Take(pageSize)    .Select(o => new { o.Id, o.Amount })    .ToListAsync();
Output
$ dotnet run -- paging      SELECT "o"."Id", "o"."Amount"      FROM "Orders" AS "o"      ORDER BY "o"."Id"      LIMIT @p1 OFFSET @p{ Id = 5, Amount = 1500 }{ Id = 6, Amount = 350 }

54.8 Comparison: Include vs Select vs AsNoTracking

TechniqueWhat it loadsTracked?Use when
IncludeFull entities + related collection (JOIN)YesYou need the entities, maybe to update them
SelectOnly the columns / aggregates you ask forNo (not entities)DTOs, summaries, list screens
AsNoTrackingFull entitiesNoRead-only endpoints returning entities
AsSplitQueryInclude split into several queriesYesTwo collection Includes multiply JOIN rows

54.9 Common mistakes

  • Calling ToListAsync first and Where after: the whole table comes into memory and the SQL has no WHERE. Put Where on the IQueryable.
  • Changing an entity loaded with AsNoTracking and calling SaveChanges: Rows saved: 0, because the ChangeTracker never knew about it.
  • Blaming EF Core for being slow: the real causes are usually N+1, extra columns or tracking; check the SQL log first.
C#
// Wrong: whole table in memory, no WHEREvar all = await db.Customers.ToListAsync();var pune = all    .Where(c => c.City == "Pune")    .ToList(); // Right: WHERE in SQL, only Pune rowsvar pune = await db.Customers    .Where(c => c.City == "Pune")    .ToListAsync();
C#
var asha = await db.Customers    .AsNoTracking()    .FirstAsync(c => c.Name == "Asha"); asha.City = "Mumbai";var saved = await db.SaveChangesAsync(); Console.WriteLine($"Rows saved: {saved}");
Output
$ dotnet run -- checkpoint      SELECT "c"."Id", "c"."City", "c"."Name"      FROM "Customers" AS "c"      WHERE "c"."Name" = 'Asha'      LIMIT 1Rows saved: 0

54.10 Rules for querying

  1. Keep SQL logging on in development; use ToQueryString when in doubt.
  2. Never query inside a loop: load in one go with Include or Select.
  3. Read-only: AsNoTracking or projection.
  4. List endpoints: OrderBy + Skip + Take.
  5. Filter in the database, call ToListAsync last.

54.11 Interview tips

  • N+1 = one query for the list, then a separate query for every row.
  • Detect it with SQL logging (LogTo) or ToQueryString; count the commands.
  • Fix it with Include (JOIN) or a Select projection that computes Count/Sum in SQL.
  • For read-only queries add AsNoTracking and pagination; mention AsSplitQuery for multiple collection Includes.