过滤时Include()的顺序是否会对性能产生影响? [英] Does the order of Include()s when filtering have an impact on performance?

查看:54
本文介绍了过滤时Include()的顺序是否会对性能产生影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很好用,我假设它会加载所有具有所有FooBar子代的实体,然后根据Foo的值过滤结果:

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();

如果是这种情况,这是否是一个有用的优化方法,首先进行过滤,然后仅对一部分实体包含Bar子级?

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();

...此外,EF是否足够聪明,以至于我在使用.Select(e.Bar)时必须包含Bar?

... also, is EF clever enough to know that when I use .Select(e.Bar) that Bar must be included?

推荐答案

事实是,在这种情况下,这实际上并不重要,因为两个Includes都被忽略了.您可以删除它们,查询将产生完全相同的SQL和结果.

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.

这是因为Include仅在应用于查询结果根实体(如果有)时才有效.这意味着对于匿名(DTO)/ViewModel等类型的投影(Select)查询,将忽略它们.仅考虑直接返回实体类型的查询,并且正如我之前所说,如果Include是从该实体类型开始的.

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.

许多人误解了Include的目的.使用导航属性进行过滤,排序,分组,选择等的查询正常运行时,根本不需要它们.它们的全部目的是

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.

在您的示例中,唯一有效的包含将是Bar的导航属性,并且必须在之后 Select(e => e.Bar)后面插入它们.它们的顺序无关紧要,SelectInclude之间的LINQ运算符也是如此,因为它们不会更改查询结果类型.

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.

这篇关于过滤时Include()的顺序是否会对性能产生影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆