views:

189

answers:

1

How to filter nested/child collections of entities when including them in EF?

Example: Let's have standard Customer-Orders association. How to load all customers and include only their last three orders in their Orders collection?

Is there something like AssociateWith function from L2S for EF?

+2  A: 

No, unfortunately the Object Services API in Entity Framework doesn't expose a way to selectively load associated entities based on a condition.

One way to solve this problem is to filter the associated entities when projecting the results in a query:

context.Customers.Select(c => new
    {
        Customer = c,
        LastOrders = c.Orders
                         .OrderByDescending(o => o.CreatedDate)
                         .Take(3)
                         .ToArray()
    }

Related resources:

Enrico Campidoglio
Add `.ToList().Select(c => c.Customer)` and you have what you wanted. Every customer will have only 3 last orders in `Orders` entity collection, but only if you didn't load orders earlier in the same context. No need to define additional type and use anonymous classes.
LukLed