How to filter nested collection Entity Framework objects?

You can’t do that directly in a “neat” way, but you have a few options.
First of all, you can explicitly load the child collection after you’ve fetched the stores. See the Applying filters when explicitly loading related entities section.

If you don’t want to make extra trips to the database, you will have to construct your own query and project the parent collection and the filtered child collections onto another object manually. See the following questions for examples:
Linq To Entities – how to filter on child entities
LINQ Query – how sort and filter on eager fetch

Edit

By the way, your first .Where(rcu=>rcu.Orders.Select(cu=>cu.Customer.Deleted==false)) attempt doesn’t work since this way you are applying a filter to your parent collection (stores) rather than the nested collection (e.g. all the stores that don’t have deleted customers).
Logically, the code filtering the nested collection should be placed in the Include method. Currently, Include only supports a Select statement, but personally I think it’s time for the EF team to implement something like:

.Include(cu => cu.Orders.Select(c => c.Customers.Where(cust => !cust.IsDeleted)));

Leave a Comment