Print Page | Close Window

The other Include()

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=2097
Printed Date: 27-Apr-2025 at 9:23pm


Topic: The other Include()
Posted By: mikewishart
Subject: The other Include()
Date Posted: 26-Aug-2010 at 9:15am
It seems everyone always uses the Include(string)

There's the other Include(func):
    public static IEntityQuery<T> Include<T>(this IEntityQuery<T> query, Expression<Func<T, object>> expr);

I can't find any examples of using this version.  I tried doing mgr.Customers.Include(c => c.Orders) and this works; however, is it possible to do something more complicated with a where clause? 
   mgr.Customers.Where(c => c.CustomerID == id)
                .Include(c => c.Orders.Where(o => o.EmployeeId == 5))

If not it seems the alternative is to use a parallel task or to get all the orders and remove those that we're not interested in from the cache after the result comes back.

Thanks!



Replies:
Posted By: sbelini
Date Posted: 26-Aug-2010 at 3:07pm
While the Entity Framework only allows you to use Include(String), DevForce goes a step further and allows you to also use simple lambda expressions (i.e. Include(c => c.Orders) - as in your example).
 
However, you can't use more complex lambda expressions. Our extension to the Include syntax (Include<TQuery>(TQuery,String)) is only an translation wrapper, that allow simple lambda’s to be translated into the Entity Framework’s string based Include syntax (Include(String)). Therefore, we can only support what EF’s Include(String) does.
 
You can still accomplish the functionality you want by using an anonymous type:
 
      mgr.Customers.Where(c => c.CustomerID == id)
        .Select(c => new { Customer = c, Orders = c.Orders.Where(o => o.EmployeeID == 5) })
        .ToList() // this is necessary so the query is executed on the server and the related objects are retrieved and stored
                     // at this point all objects satisfying the query (Customer and Orders) are in the cache
        .Select(a => a.Customer); // this is executed locally (data already in the cache)
 
The above will ensure that the objects related  (Orders where [EmployeeID] == 5) to the primary target of this query (Customer where [CustomerID] == id) are also stored in the entity cache.


Posted By: mikewishart
Date Posted: 26-Aug-2010 at 3:59pm
Perfect!  Nice tip/trick. 
Thanks



Print Page | Close Window