New Posts New Posts RSS Feed: The other Include()
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

The other Include()

 Post Reply Post Reply
Author
mikewishart View Drop Down
Groupie
Groupie
Avatar

Joined: 26-Feb-2010
Location: Reno, NV
Posts: 49
Post Options Post Options   Quote mikewishart Quote  Post ReplyReply Direct Link To This Post Topic: The other Include()
    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!
Back to Top
sbelini View Drop Down
IdeaBlade
IdeaBlade
Avatar

Joined: 13-Aug-2010
Location: Oakland
Posts: 786
Post Options Post Options   Quote sbelini Quote  Post ReplyReply Direct Link To This Post 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.
Back to Top
mikewishart View Drop Down
Groupie
Groupie
Avatar

Joined: 26-Feb-2010
Location: Reno, NV
Posts: 49
Post Options Post Options   Quote mikewishart Quote  Post ReplyReply Direct Link To This Post Posted: 26-Aug-2010 at 3:59pm
Perfect!  Nice tip/trick. 
Thanks
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down