Playing with Expression Trees Part 1
I recently looked into an extremely powerful low-level tool that makes C# rise high among the contemporary languages - Expression Trees.
If you use Reflector to look into the IQueryable interface, you'd see that it shows you the following code.
public interface IQueryable : IEnumerable
{
// Properties
Type ElementType { get; }
Expression Expression { get; }
IQueryProvider Provider { get; }
}
One of it's properties is Expression which is nothing but a data structure. The executable code found in the query expression (inside the IQueryable object) is represented by this expression.
The obvious question is why an Expression? An Expression is just a data structure that will be translated into appropriate SQL code when required. This explains lazy loading in Linq.
Let's look at the following example. I just created a Linq to Sql class Customers.dbml and pulled over the Customers entity to the designer. Rest is magic that visual studio does for ue.
Problem: Output the name of all Customers whose addresses are not there in the database.
var customersDataContext = new CustomersDataContext();
var filteredCustomers= customersDataContext.Customers.Where(c => (c.Address==null || c.Address==string.Empty));
foreach (var customer in filteredCustomers)
{
Console.WriteLine(customer.ContactName);
}
If you hover over the 'var' keyword left of filteredCustomers, you'd see that the type is IQueryable<Customer>.
What if we change the code to
var customersDataContext = new CustomersDataContext();
var filteredCustomers= customersDataContext.Customers.Where(c => string.IsNullOrEmpty(c.Address));
foreach (var customer in filteredCustomers)
{
Console.WriteLine(customer.ContactName);
}
We get the following exception.
Method 'Boolean IsNullOrEmpty(System.String)' has no supported translation to SQL.
The exception makes it pretty obvious that when the Expression gets translated to SQL there is no supported translation for the IsNullOrEmpty method on String.
This would give you a fair idea of what amount of work it would take to write your own Expression trees. ..... To be continued.