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

无人久伴 提交于 2019-12-11 13:07:31

问题


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:


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.



来源:https://stackoverflow.com/questions/52767559/does-the-order-of-includes-when-filtering-have-an-impact-on-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!