Entity Framework Core Interview Question #23
What is deferred execution in EF Core LINQ queries?
EF Core Fundamentals & DbContext Junior Beginner
Quick Interview Answer
Many LINQ operators build an IQueryable expression without immediately sending a query to the database. The SQL is executed when the query is materialized or otherwise enumerated.
Detailed Explanation
Many LINQ operators build an IQueryable expression without immediately sending a query to the database. The SQL is executed when the query is materialized or otherwise enumerated.
Methods such as ToListAsync, FirstOrDefaultAsync, SingleAsync, CountAsync, and iteration can trigger execution.
Deferred execution allows a query to be composed incrementally, but developers should avoid accidentally executing essentially the same database query multiple times.
Code Example
IQueryable<Product> query = db.Products;
query = query.Where(p => p.IsActive);
if (minimumPrice.HasValue)
query = query.Where(p => p.Price >= minimumPrice.Value);
// Database query executes here.
var products = await query.ToListAsync();