EF: Include with where clause

Several guys ask me if it’s possible to add a condition in the Include method and the answer is no.

However you can do an equivalent like this:

from cWithP in

    (from c in context.Categories

     select new

     {

         Category = c,

         Products = from p in c.Products

                    where p.UnitPrice > 20

                    select p

     }).AsEnumerable()

select cWithP.Category;

or the condensed equivalent:

context.Categories.Select(c => new { Category = c, Products = c.Products.Where(p => p.UnitPrice > 20) }).AsEnumerable().Select(cp => cp.Category);

Published Wed, Oct 7 2009 0:10 by Matthieu MEZIL

Comments

# re: EF: Include with where clause

Thank you very much for this excellent solution.

Friday, February 12, 2010 9:40 AM by sanvir

# re: EF: Include with where clause

Thanks for the post.  It was very helpful!

Monday, April 04, 2011 12:21 PM by Cindi

# re: EF: Include with where clause

Hi,

This does not actually work.

It appears to work because the EF context only has a subset of the entities loaded.

If you subsequently load more of the child entities that will be magically added to the parent, and will be included in the attached children breaking your code.

ChildTable.Select(_ => _).Load();

var p = ParentTable.Select(o => new { Parent = o, Children = o.Children.Where(_ => _.Name.Length == 1)}).AsEnumerable().Select (_p => _p.Parent);

p.Dump();

You will get all the child entities, if you like it or not.

Turn change tracking off, and you get no child entities.

var p = ParentTable.AsNoTracking().Select(o => new { Parent = o, Children = o.Children.Where(_ => _.Name.Length == 1)}).AsEnumerable().Select (_p => _p.Parent);

p.Dump();

The query just 'appears' to work, and you need to be careful of what is or is not attached to the context at the time you execute the query.

Friday, May 18, 2012 2:07 AM by Craig

# re: EF: Include with where clause

Hi

Entity Framework associations work like this!

The navigation properties are always filled with what you have in your context cache.

Friday, May 18, 2012 2:22 AM by Matthieu MEZIL

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: