Archive

Posts Tagged ‘LINQ’

IQueryable, ObjectQuery and Composing LINQ to Entity Framework Queries

March 31, 2011 1 comment

As discussed in a previous post, Entity Framework and WCF work very well together, but you need to be careful about LazyLoading being switched on automatically as this can serialise the entire object graph when querying via WCF which could have a very serious impact on performance.

With LazyLoading turned off however, the problem with WCF is how to bring back all the related data that is required. The answer is to use the ObjectQuery.Include method. In order to use this with LINQ you need to cast your IQueryableto an ObjectQuery.

This additionally allows you to compose queries from logical sections and finally include the additional extra entities that will be required in the results.

using (AdventureWorksLT2008Entities context = new AdventureWorksLT2008Entities())
{
    context.ContextOptions.LazyLoadingEnabled = false;

    // simple example to select some customers
    var customersQuery = from c in context.Customers
                         where c.LastName.StartsWith("B")
                         select c;

    // additional composition of the query which could be conditional
    var customersWithOrdersQuery = from c in customersQuery
                                   where c.SalesOrderHeaders.Count > 0
                                   select c;

    // include the SalesOrderHeaders in the results
    var customerOrders = (customersWithOrdersQuery as ObjectQuery)
        .Include("SalesOrderHeaders");

    foreach (Customer c in customerOrders)
    {
        Console.WriteLine("First Name: {0}, Last Name: {1}", c.FirstName, c.LastName);
        foreach (SalesOrderHeader soh in c.SalesOrderHeaders)
        {
            Console.WriteLine("    SalesOrderID: {0}, OrderDate: {1}, TotalDue: {2}", soh.SalesOrderID, soh.OrderDate, soh.TotalDue);
        }
    }
}

Listing 1 – Example of composing queries and ObjectQuery<T>.Include