问题描述
这很好用,我假设它会加载所有具有所有Foo
和Bar
子代的实体,然后根据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 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 the Include
s start from that entity type.
许多人误解了Include
的目的.使用导航属性进行过滤,排序,分组,选择等的查询正常运行时,根本不需要它们.它们的全部目的是加载相关实体.
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.
在您的示例中,唯一有效的包含将是Bar
的导航属性,并且必须在之后 Select(e => e.Bar)
后面插入它们.它们的顺序无关紧要,Select
和Include
之间的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()的顺序是否会对性能产生影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!