How LINQ query is compiled to Expression Trees?

In LINQ, a query expression is compiled to expression trees or to delegates, depending on the type that is applied to query result. The IEnumerable<T> type LINQ queries are compiled to delegates and IQueryable or IQueryable<T> type LINQ queries are compiled to expression trees.
In short, LINQ queries that execute in process are compiled into delegates while the queries that execute out of process are compiled into expression trees.
In LINQ, domain-specific queries (like LINQ to SQL, LINQ to Entity) are result into IQueryable<T> type. The C# and Visual Basic compilers compile these queries into code that builds an expression trees at runtime. Then query provider traverse the expression tree and translate it into a query language (like T-SQL) which is appropriate for that data source.
Consider the following LINQ to SQL query expression:

var query = from c in db.Customers
            where c.City == "Delhi"
            select new { c.City, c.CompanyName };

Here query variable, returned by this LINQ query is of type IQueryable and the declaration of IQueryable is as:

public interface IQueryable: IEnumerable {
	Type ElementType {
		get;
	}
	Expression Expression {
		get;
	}
	IQueryProvider Provider {
		get;
	}
}

As you can see, IQueryable contains a property of type Expression which holds the expression tree and represents data structure equivalent to the executable code found in a query expression. The IQueryProvider type property hold the LINQ provider (like LINQ to SQL, LINQ to Entity etc.) and based on LINQ provider query is translated into an appropriate query (like T-SQL query). The Type property represents the type of the element(s) that are returned when the expression tree is executed.
In this way, the above code is never actually executed inside your program. It is first translated into the following SQL statement and then executed on SQL Server side.

SELECT
[t0].[City],
[t0].[CompanyName]
FROM
[dbo].[Customers] AS [t0]
WHERE
[t0].[City] = @p0
Tagged , . Bookmark the permalink.

Leave a Reply