Entity Framework Core Interview Question #24

What is the difference between IQueryable and IEnumerable when using EF Core?

EF Core Fundamentals & DbContext Junior Beginner

Quick Interview Answer

IQueryable represents a query expression that a provider such as EF Core can translate and execute against the database. Filtering, projection, ordering, and pagination added while the query remains IQueryable can therefore be translated into SQL.

Detailed Explanation

IQueryable represents a query expression that a provider such as EF Core can translate and execute against the database. Filtering, projection, ordering, and pagination added while the query remains IQueryable can therefore be translated into SQL.

IEnumerable represents in-memory enumeration semantics. Once data has been materialized, later LINQ operations generally execute in application memory.

Materializing too early can cause unnecessary rows and columns to be transferred from the database. Keep filtering and projection in the database query when possible.

Code Example

// Filtering occurs in SQL.
var query = db.Products
    .Where(p => p.IsActive)
    .Select(p => new { p.Id, p.Name });

var result = await query.ToListAsync();

// result is now in memory.