Expression tree as name suggests is nothing but expressions arranged in a tree-like data structure. Each node in an expression tree is an expression. This is particularly useful for LINQ providers like Entity Framework that translate LINQ queries into SQL.
Expressions - Expression represents a piece of code in a way that can be executed or analyzed. In .NET, expressions are generally instances of the System.Linq.Expressions.Expression<T> class, where T is a delegate type.
When you use LINQ queries, the LINQ provider translates your LINQ expressions into SQL queries.
For instance
var query = dbContext.Employees.Where(e => e.Age > 30);
In the background, this LINQ query is represented as an expression tree. The LINQ provider (like Entity Framework) will convert this expression tree into a SQL query.
SELECT * FROM Employees WHERE Age > 30
Here’s a basic example demonstrating how to create and use an expression tree:
In this example,
Example
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
// Define parameters
ParameterExpression param = Expression.Parameter(typeof(int), "x");
// Create a constant expression
ConstantExpression constant = Expression.Constant(5);
// Create a binary expression (x > 5)
BinaryExpression body = Expression.GreaterThan(param, constant);
// Create a lambda expression (x => x > 5)
Expression> lambda = Expression.Lambda>(body, param);
// Compile and execute the lambda expression
Func compiledLambda = lambda.Compile();
bool result = compiledLambda(10); // True
Console.WriteLine(result); // Output: True
}
}
Output