LINQ Interview Question #103
Why does IQueryable use expression trees?
LINQ Performance, EF Core LINQ, Expressions & Advanced Queries Senior Advanced
Quick Interview Answer
IQueryable must provide the query provider with a structured description of the requested operations. Expression trees provide that structure.
Detailed Explanation
IQueryable must provide the query provider with a structured description of the requested operations. Expression trees provide that structure.
A provider such as Entity Framework Core can inspect member access, comparisons, method calls, projections, and other supported expressions, then translate them into SQL. Arbitrary compiled .NET code cannot generally be translated this way.
Code Example
IQueryable<Product> query = db.Products
.Where(p => p.IsActive && p.Price > 500)
.OrderBy(p => p.Name);
// Provider inspects the expression tree at execution.