It is common in many applications to execute structurally-similar queries many times. In such cases, it is possible to increase performance by compiling the query once, and executing it several times in the application with different parameters. This result is obtained in LINQ to SQL by using the CompiledQuery
class.
The following code shows how to define a compiled query:
Func<NorthwindDataContext, string, IQueryable<Product>> fn = CompiledQuery.Compile((NorthwindDataContext db2, string category) => from p in db2.Products where p.Category.CategoryName == category select p); var products1 = fn(db, "Beverages"); Console.WriteLine("Total products in category Beverages: {0}", products1.Count()); var products2 = fn(db, "Seafood"); Console.WriteLine("Total products in category Seafood: {0}", products2.Count());
As you can see, a compiled query is actually a function. The function contains a compiled LINQ query expression, and can be called just like a regular function.