Compiled query
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 Entities by using the CompiledQuery
class.
The following code shows how to define a compiled query:
static void TestCompiledQuery() { NorthwindEntities NWEntities = new NorthwindEntities(); Func<NorthwindEntities, string, IQueryable<Product>> fn = CompiledQuery.Compile((NorthwindEntities NW, string category) => from p in NW.Products where p.Category.CategoryName == category select p); var products1 = fn(NWEntities, '"Beverages'"); Console.WriteLine('"Total products in category Beverages: {0}'", products1.Count()); var products2 = fn(NWEntities, '"Seafood'"); Console.WriteLine('"Total products in category Seafood: {0}'", products2.Count(...