Query translation and loading
Query translation and loading
EF Core translates a query expression tree into provider-specific commands. The database handles supported filters, joins and aggregates; the client materializes results. Query shape determines both correctness and the amount of work performed.
IQueryable is a query description, not a guarantee of translation. An unsupported expression outside the final projection normally causes an exception; deliberate client processing should follow a bounded, server-filtered result. ToQueryString is a diagnostic representation, not necessarily the exact command issued by a terminal operation. Use parameterized LINQ or interpolated EF SQL APIs rather than concatenating untrusted text. Eager loading uses Include; explicit loading uses Entry and Load; lazy loading requires configuration and can trigger unexpected queries. A loop that loads each related collection separately can cause one initial query plus N additional queries. Prefer a scalar projection when only a summary is needed. Multiple collection Includes can multiply joined rows; split queries trade this for extra round trips and possible consistency differences. Measure query count, result size and database plans. Compiled queries can reduce repeated EF overhead, but do not fix inefficient SQL. With ExecuteUpdate and ExecuteDelete, supported changes execute immediately and bypass normal tracking; use bounded predicates and reconcile stale entities.
Baseline: .NET 10 / C# 14, Microsoft.EntityFrameworkCore.Sqlite 10.0.15 (published package, restore and advisory checks pending). Each independent project includes its own complete source and project file. In an approved environment with a reviewed SDK and packages, restore from approved sources, then run dotnet build --no-restore and dotnet run --no-build in the fixture directory. Except for the migration-operation inspection, each uses its own open SQLite in-memory connection, synthetic catalog and schema created by EnsureCreated. No external database, account or credential is required. Expected results are reasoned, not executed.
Inspect the translated predicate
Filter and project in a query before materializing. Check only a diagnostic marker, not exact SQL formatting.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var query = db.Books.Where(b => b.Stock > 0).Select(b => b.Title);Console.WriteLine(query.ToQueryString().Contains("WHERE", StringComparison.OrdinalIgnoreCase));Console.WriteLine(query.Single());class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
TrueAtlasThe selected provider should translate the filter; actual SQL and execution require a runtime test.
Load related rows eagerly
Use a fresh tracker and Include for a category and its books.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var category = db.Categories.Include(c => c.Books).Single();Console.WriteLine(category.Name);Console.WriteLine(category.Books.Count);class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
Science2The query loads the relationship; the collection order is not guaranteed.
Project a count instead of repeated loads
Ask for category names and counts rather than materializing book entities.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();var summaries = db.Categories.OrderBy(c => c.Id) .Select(c => new { c.Name, Total = c.Books.Count }).ToList();foreach (var row in summaries) Console.WriteLine($"{row.Name}:{row.Total}");Console.WriteLine(db.ChangeTracker.Entries().Count());class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
Science:20The scalar aggregate can be translated by SQLite; there are no tracked entities from this projection.
Apply the concept
A page shows 20 categories with book counts. Compare per-category explicit loads, eager loading, and aggregate projection. Write a measurement plan.
Use the manual practice and knowledge check to reason about the boundary. Do not apply these examples to a production database.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Query translation and loading — knowledge check
Apply the lesson concepts to the following scenarios.
What is ToQueryString for?
What commonly produces N+1 queries?
What is best to compare for a category count list?
What happens to unsupported filters outside the final projection?
What is a split-query tradeoff?