Welcome to Bilal Haidar [MVP, MCT] Official Blog Sign in | Join | Help

Compiled Queries in dLinq

In an API I use in my applications at work, we have the notion of StoredQuery. We prepare a query against the database, store it as a StoredQuery, then execute the query. Why do we need to save the query expression? Maybe at some other time, we need to execute the same query, off course not neceessarily same results. So here the StoredQuery comes in handy!
I found today that DLinq has the same notion of saving or compiling a query for later use. How do you create a compiled query? Here is a sample:

static class Queries
{
 public static Func<Northwind, string, IQueryable<Customer>> CustomersByCity =
  CompiledQuery.Compile((Northwind db, string city) =>
   from c in db.Customers where c.City == city select c);
}

Now you have created a compiled query, you can notice that the Func delegate takes as input the DataContext, the city, and the result is IQueryable of customers.

How to use the above compiled query?

public IEnumerable<Customer> GetCustomersByCity(string city) {
 Northwind db = new Northwind();
 return Queries.CustomersByCity(myDb, city);
}

You define a new method, inside it you create a DataContext instance, and finally you call the compiled query!

Hope this helps,
Regards

Published Saturday, July 28, 2007 5:00 AM by BilalHaidar [MVP]
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Compiled Queries in dLinq

Thanks for the info, i managed to get them working a blogged detailed about them here:

http://bantimon.blogspot.com/2007/08/linq-to-sql-dlinq-compiled-queries.html

Friday, August 17, 2007 3:02 PM by Antimon

Leave a Comment

(required) 
required 
(required)