Does the order of Include()s when filtering have an impact on performance?

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?

1 answer

  • answered 2018-10-11 20:12 Ivan Stoev

    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 Includes 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 the Includes start from that entity type.

    Many people misunderstand the purpose of the Includes. 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 after Select(e => e.Bar). Their order is unimportant, as well as the LINQ operators between Select and Include as sooon as they don't change the query result type.