Expression trees and translation
Expression trees and translation
An expression tree describes operations as typed nodes. A provider can inspect these nodes instead of invoking arbitrary compiled code. Building a valid C# expression tree, executing it locally and translating it into another query language are three separate capabilities.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Inspect the structure
Expression<Func<int,bool>> represents a predicate tree. A BinaryExpression has operands and an operation kind. Reading these properties is more robust than parsing the diagnostic text returned by ToString.
using System;using System.Linq.Expressions;Expression<Func<int, bool>> rule = n => n >= 10;var body = (BinaryExpression)rule.Body;Console.WriteLine(body.NodeType);Console.WriteLine(body.Left.NodeType);Console.WriteLine(body.Right.NodeType);The comparison has a parameter on the left and a literal constant on the right. The cast is safe for this known lambda shape, not for arbitrary predicates.
Expected output (reasoned, not executed):
GreaterThanOrEqualParameterConstantBuild and execute a predicate
Expression factory methods create tree nodes explicitly. Reuse the same ParameterExpression instance throughout the lambda to bind its references. Compile produces a delegate for local execution. It does not ask a database to translate the tree.
using System;using System.Linq;using System.Linq.Expressions;var n = Expression.Parameter(typeof(int), "n");var lower = Expression.GreaterThanOrEqual(n, Expression.Constant(3));var upper = Expression.LessThanOrEqual(n, Expression.Constant(6));var tree = Expression.Lambda<Func<int, bool>>(Expression.AndAlso(lower, upper), n);var predicate = tree.Compile();Console.WriteLine(string.Join(",", new[] { 1, 3, 5, 6, 9 }.Where(predicate)));The combined expression tests both inclusive endpoints. Compile is used once and the resulting delegate is reused.
Expected output (reasoned, not executed):
3,5,6Recognize a translation risk
A method call may be represented in a tree even if a database provider cannot translate it. For example, EF Core generally rejects untranslatable filters rather than silently fetching all rows; some top-level projections can be evaluated on the client. Check the exact provider and version, inspect generated queries, and test against a real fixture.
using System;using System.Linq;using System.Linq.Expressions;Expression<Func<int, bool>> predicate = n => Rules.IsEligible(n);Console.WriteLine(predicate.Body.NodeType);Console.WriteLine(string.Join(",", new[] { 2, 3, 4 }.AsQueryable().Where(predicate)));static class Rules{ public static bool IsEligible(int value) => value % 2 == 0;}The local queryable can evaluate the method. This gives no evidence that a relational provider can translate Rules.IsEligible.
Expected output (reasoned, not executed):
Call2,4Common mistakes and edge cases
Do not confuse an expression-bodied lambda with universal expression-tree compatibility: statement-bodied lambdas and some language constructs cannot be converted by the compiler. Do not equate Compile with SQL generation. Repeated compilation has costs; measure before introducing a cache. Captured values may appear as member accesses rather than literal constants.
Practice and recap
Build a tree for n > 2 && n < 8, inspect its root NodeType, compile it and filter [2,3,7,8]. Describe what still needs testing before using it with EF Core.
Hint: Use Expression.AndAlso or an expression lambda; use the same parameter instance if building manually.
Learning objective: Identify a provider-dependent operation. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expression trees and translation — knowledge check
Apply the lesson concepts to the following scenarios.
What does an expression tree store?
Which node kind is the root of n >= 10?
Why reuse a ParameterExpression instance?
What does Compile return for Expression<Func<int,bool>>?
A custom method works in local AsQueryable. What follows?