Jul 28 2007

Compiled Queries in dLinq

Category: DLinq | LinqBil@l @ 15:00

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,

Tags: ,

Comments are closed