Compiled Queries in LINQ to Entities c#

263
Views
1
Answers

How do or can we compile queries in LINQ to Entities?

edit | flag
Mad Maddy
Asked on: Jan 31, 2012 at 10:16PM

1 Answers

115
5
115

The CompiledQuery class provides compilation and caching of queries for reuse. Conceptually, this class contains a CompiledQuery's Compile method with several overloads. Call the Compile method to create a new delegate to represent the compiled query. The Compile methods, provided with a ObjectContext and parameter values, return a delegate that produces some result (such as an IQueryable instance). The query compiles once during only the first execution. The merge options set for the query at the time of the compilation cannot be changed later. Once the query is compiled you can only supply parameters of primitive type but you cannot replace parts of the query that would change the generated SQL. For more information, see Entity Framework Merge Options and Compiled Queries

The following example compiles and then invokes a query that accepts a Decimal input parameter and returns a sequence of orders where the total due is greater than or equal to $400.00:

static readonly Func<AdventureWorksEntities, Decimal, IQueryable> s_compiledQuery2 = 
   
CompiledQuery.Compile<AdventureWorksEntities, Decimal, IQueryable>(
           
(ctx, total) => from order in ctx.SalesOrderHeaders
                           
where order.TotalDue >= total
                           
select order);

static void CompiledQuery2()
{            
   
using (AdventureWorksEntities context = new AdventureWorksEntities())
   
{
       
Decimal totalDue = 200.00M;

       
IQueryable orders = s_compiledQuery2.Invoke(context, totalDue);

       
foreach (SalesOrderHeader order in orders)
       
{
           
Console.WriteLine("ID: {0}  Order date: {1} Total due: {2}",
                order
.SalesOrderID,
                order
.OrderDate,
                order
.TotalDue);
       
}
   
}            
}
edit | flag
Gokul A
Answered on: Jan 31, 2012 at 10:22PM

Post your Answer

Search

Welcome to Ask Amoeba!
This is 100% free and interactive site for sharing professional Questions and Answers, Opensource projects, Interview questions.
Learners, beginners, Experts stop and share your knowledge and ideas!

Browse Categories

Browse Tags