This works fine, and I assume it loads all the entities with all the Foo
and Bar
children, then filters the results based on Foo
's value:
var baz = "sillystring";
context.Entities
.Include(e => e.Foo)
.Include(e => e.Bar)
.Where(e.Foo == baz)
.Select(e.Bar)
.ToList();
So if that's the case, is this a helpful optimization where the filtering is done first and then Bar
children are included only for a subset of entities?
var baz = "sillystring";
context.Entities
.Include(e => e.Foo)
.Where(e.Foo == baz)
.Include(e => e.Bar) // moved to after the filter
.Select(e.Bar)
.ToList();
... also, is EF clever enough to know that when I use .Select(e.Bar)
that Bar
must be included?
The truth is that it really doesn't matter in this case because both
Includes
are ignored. You could remove them and the query will produce exactly the same SQL and result.This is because
Include
s are in effect only when applied to the query result root entity (if any). Which means they are ignored for projection (Select
) queries into anonymous / DTO / ViewModel etc. types. Only queries returning directly entity types are considered, and as I said before, if theInclude
s start from that entity type.Many people misunderstand the purpose of the
Include
s. They are not needed at all for correctly functioning of the queries that use navigation properties for filtering, ordering, grouping, selecting etc. All their purpose is to Load Related Entities.In your sample, the only valid includes would be the navigation properties of the
Bar
, and they must be inserted afterSelect(e => e.Bar)
. Their order is unimportant, as well as the LINQ operators betweenSelect
andInclude
as sooon as they don't change the query result type.