← Tutti gli articoli

Compiled Query in the Entity Data Framework

27 agosto 2012  · EDF · Article  ·  371 visite

Improve Entity Data Framework performance in ripetitive query

The translation from LINQ to Sql statements requires CPU and time resources. It is possible to compile a LINQ query
  1. static Func<MaragnaEntities, string, IQueryable<Contents>>  
  2. contenuti =  
  3.   CompiledQuery.Compile<MaragnaEntities, string, IQueryable<Contents>>(  
  4.     (context, title) =>  
  5.       from c in context.Contents  
  6.       where c.Title == title  
  7.       select c  
  8.   );  

 
In this code snippet, the LINQ query is compiled with the help of the Compile method of the CompiledQuery class and stored in a static field called contenuti.
The compiled query itself is a lambda expression, which takes an object context as its first parameter, a title as its second, and returns an IQueryable of Contents.

 

  1. using  (MaragnaEntities context =  new  MaragnaEntities())  
  2. {  
  3.   var query = contenuti.Invoke(context, "ASP.NET");  
  4.   foreach (Contents c in query  
  5.     Console.WriteLine(c.ContactName);  
  6. }  
  7.