Linq2Entities + Entity Framework查询优化:.Where()vs. Linq where

|| 我对实体框架模型有一个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视图进行分组(测试数据库中有7300万条记录,生产中几乎有8亿条记录)。我原本希望将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]
在我的上下文中直接对集合应用ѭ5与在Linq查询中使用ѭ6为什么会有区别?我认为这将以相同的方式解析到表达式树中。 附言在一个旁注中,将两个查询都放入SQL Server Management Studio中并比较了查询执行计划,我很惊讶地发现执行计划与上述两种方式完全相同。 SQL的查询计划优化器确实是不可思议的!     
已邀请:
这些查询之间的区别在于表示您使用的构造。第一个查询的评估为
 (from e3 in context.Entity3) where e3.Fied1 == value
而第二个查询被评估为
 from e3 in (context.Entity3.Where(e => e.Field1 == value))
虚线语法具有优先权,因为它被当作单独的表达式子树,必须将其构造并附加到外部查询的表达式树上。您可以将其视为子查询,即使它不一定像您的示例所示那样最后还是子查询。     

要回复问题请先登录注册