Advertisement
Intermediate C# Lesson 8 of 8

Lesson 8: LINQ with Entity Framework & Deferred Execution

In this final lesson, you'll see how LINQ works with Entity Framework Core and how deferred execution affects database queries and performance.

Advertisement

LINQ and EF Core

Entity Framework Core exposes IQueryable<T> for DbSet queries. LINQ expressions are translated into SQL before execution.

using var context = new AppDbContext();

var activeUsers = context.Users
    .Where(user => user.IsActive)
    .OrderBy(user => user.LastLogin)
    .Select(user => new { user.Id, user.Email });

var list = activeUsers.ToList();

Deferred Execution in EF Core

Until you call a terminal method like ToList(), First(), or Count(), EF Core only builds the SQL query. The database is contacted when the sequence is actually enumerated.

var query = context.Products.Where(p => p.Stock > 0);

// No SQL executed yet

foreach (var product in query)
{
    Console.WriteLine(product.Name); // SQL executes here
}

Use AsNoTracking for Read-Only Queries

AsNoTracking() improves performance when you only need read-only results and do not update entities.

var items = context.Products
    .AsNoTracking()
    .Where(p => p.IsPublished)
    .ToList();

Query Composition

LINQ lets you compose queries in steps. Each call adds to the expression tree until execution.

var query = context.Orders.Where(order => order.IsPaid);
query = query.Where(order => order.Total >= 100);
query = query.OrderByDescending(order => order.PlacedAt);

var recentLargeOrders = query.ToList();

🧠 Quick Check — Lesson 8

When does EF Core execute an IQueryable query?

Lesson Summary

EF Core uses IQueryable to translate LINQ expressions into SQL.

Deferred execution means the query runs only when results are consumed.

AsNoTracking() improves performance for read-only EF Core queries.

Query composition lets you build expressive database queries in stages.