Home > C# > IQueryable, ObjectQuery and Composing LINQ to Entity Framework Queries

IQueryable, ObjectQuery and Composing LINQ to Entity Framework Queries


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

Advertisements
  1. No comments yet.
  1. June 2, 2011 at 8:02 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: