CompiledQuery Class

CompiledQuery Class

Represents a cached LINQ to Entities query.

Namespace:  System.Data.Objects
Assembly:  System.Data.Entity (in System.Data.Entity.dll)

public sealed class CompiledQuery

Provides for compilation and caching of queries for reuse. Conceptually this class contains a single Compile method with several overloads. You call the Compile method to create a new delegate to represent the compiled query. The delegate, when invoked with the ObjectContext input parameter and other parameter values, produces some result (such as an IQueryable<T> instance). The query is translated and cached when the delegate is invoked for the first time.

The following example compiles and then invokes a query that accepts DateTime and Decimal input parameters and returns a sequence of orders where the order date is later than March 8, 2003 and the total due is less than $300.00:

static readonly Func<AdventureWorksEntities, DateTime, Decimal, IQueryable<SalesOrderHeader>> s_compiledQuery5 = 
    CompiledQuery.Compile<AdventureWorksEntities, DateTime, Decimal, IQueryable<SalesOrderHeader>>(
            (ctx, orderDate, totalDue) => from product in ctx.SalesOrderHeader
                                          where product.OrderDate > orderDate 
                                             && product.TotalDue < totalDue
                                          orderby product.OrderDate
                                          select product);

static void CompiledQuery5()
    using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
        DateTime date = new DateTime(2003, 3, 8);
        Decimal amountDue = 300.00M;

        IQueryable<SalesOrderHeader> orders = s_compiledQuery5.Invoke(AWEntities, date, amountDue);

        foreach (SalesOrderHeader order in orders)
            Console.WriteLine("ID: {0} Order date: {1} Total due: {2}", order.SalesOrderID, order.OrderDate, order.TotalDue);


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5 SP1

Community Additions

© 2016 Microsoft