Linq2Entities + Entity Framework查询优化:.Where()与Linq在哪里
我对我的实体框架模型有一个Linq查询,就像这样:
from e1 in context.Entity1
from e2 in context.Entity2
from e3summary in
from e3 in context.Entity3
where e3.Field1 = value // <-- this is the line in question
group e3 by new { e3.Field1, e3.Field2, e3.Field3 }
into e3group
select new
{
e3group.Key.Field1,
e3group.Key.Field2,
e3group.Key.Field3,
Total = e3group.Sum(o => o.Field4)
}
where
// conditions on e1 and joining e1, e2, and e3summary
...
select e1;
生成的SQL从我的e3表(实际上是数据库中的一个视图)中选择一切作为派生表,然后对派生表应用where子句,对其进行分组,并加入到其他结果中。 这几乎正是我想要的,除了我认为我不需要整个e3视图进行分组(它是我的测试数据库中的73M记录,几乎是800M的产品)。 我期待在我的Linq查询中的WHERE子句应用在最内层,但是我得到了(我只包括相关部分):
...
INNER JOIN (SELECT
[Extent3].[Field1] AS [K1],
[Extent3].[Field2] AS [K2],
[Extent3].[Field3] AS [K3],
SUM([Extent3].Field4] AS [A1]
FROM (SELECT
[e3].[ID] AS [ID],
[e3].[Field1] AS [Field1],
[e3].[Field2] AS [Field2],
[e3].[Field3] AS [Field3],
[e3].[Field4] AS [Field4],
[e3].[Field5] AS [Field5],
[e3].[Field6] AS [Field6],
[e3].[Field7] AS [Field7],
[e3].[Field8] AS [Field8]
FROM [dbo].[e3] AS [e3]) AS [Extent3]
WHERE ([Extent3].[Field1] = @p__linq__0)
GROUP BY [Extent3].[Field1], [Extent3].[Field2], [Extent3].[Field3] ) AS [GroupBy1]
...
我改变了我的Linq查询
from e3 in context.Entity3
where e3.Field1 = value // <-- this is the line in question
至
from e3 in context.Entity3.Where(e => e.Field1 = value)
这创建了我最初期望的内容,即最内层的WHERE子句:
...
FROM [dbo].[e3] AS [e3] WHERE [e3].Field1] = @p__linq__0) AS [Extent3]
GROUP BY [Extent3].[Field1], [Extent3].[Field2], [Extent3].[Field3] ) AS [GroupBy1]
为什么在我的上下文中直接应用.Where([condition])
与在我的上下文中收集某个where [condition]
之间存在差异? 我会认为这将以相同的方式被解析到表达式树中。
PS在旁注中,将两个查询放入SQL Server Management Studio并比较查询执行计划,我惊讶地发现执行计划无论如何都是完全相同的。 SQL的查询计划优化器确实令人难以置信!
这些查询之间的区别在于表示您使用的构造。 第一个查询评估为
(from e3 in context.Entity3) where e3.Fied1 == value
而第二个查询被评估为
from e3 in (context.Entity3.Where(e => e.Field1 == value))
虚线语法优先,因为它被视为单独的表达式子树,必须构造并附加到外部查询的表达式树上。 您可以将其视为子查询,即使最后不必像子查询那样进行子查询,如示例中所示。
链接地址: http://www.djcxy.com/p/93927.html上一篇: Linq2Entities + Entity Framework query optimization: .Where() vs. Linq where
下一篇: how to insert Hierarchical data from xml to oracle tables