为什么Entity Framework会生成嵌套的SQL查询?

Sim*_*röm 21 c# mysql linq entity-framework entity-framework-5

为什么Entity Framework会生成嵌套的SQL查询?

我有这个代码

    var db = new Context();
    var result = db.Network.Where(x => x.ServerID == serverId)
        .OrderBy(x=> x.StartTime)
        .Take(limit);
Run Code Online (Sandbox Code Playgroud)

哪个产生了这个!(注意双选语句)

SELECT
`Project1`.`Id`, 
`Project1`.`ServerID`, 
`Project1`.`EventId`, 
`Project1`.`StartTime`
FROM (SELECT
`Extent1`.`Id`, 
`Extent1`.`ServerID`, 
`Extent1`.`EventId`, 
`Extent1`.`StartTime`
FROM `Networkes` AS `Extent1`
 WHERE `Extent1`.`ServerID` = @p__linq__0) AS `Project1`
 ORDER BY 
`Project1`.`StartTime` DESC LIMIT 5
Run Code Online (Sandbox Code Playgroud)

我应该更改什么才能产生一个选择语句?我正在使用MySQL和Entity Framework与Code First.

更新

无论传递给OrderBy()方法的参数类型如何,我都有相同的结果.

更新2:定时

Total Time (hh:mm:ss.ms)    05:34:13.000
Average Time (hh:mm:ss.ms)  25:42.000
Max Time (hh:mm:ss.ms)  51:54.000
Count   13
First Seen  Nov 6, 12 19:48:19
Last Seen   Nov 6, 12 20:40:22
Run Code Online (Sandbox Code Playgroud)

原始查询:

SELECT `Project?`.`Id`, `Project?`.`ServerID`, `Project?`.`EventId`, `Project?`.`StartTime` FROM (SELECT `Extent?`.`Id`, `Extent?`.`ServerID`, `Extent?`.`EventId`, `Extent?`.`StartTime`, FROM `Network` AS `Extent?` WHERE `Extent?`.`ServerID` = ?) AS `Project?` ORDER BY `Project?`.`Starttime` DESC LIMIT ?
Run Code Online (Sandbox Code Playgroud)

我使用一个程序从MySQL中的当前进程中获取快照.

其他查询同时执行,但是当我将其更改为一个SELECT语句时,它永远不会超过一秒.也许我还有别的东西在继续; 我问'因为我不是这样的...

更新3:解释声明

实体框架生成

'1', 'PRIMARY', '<derived2>', 'ALL', NULL, NULL, NULL, NULL, '46', 'Using filesort'
'2', 'DERIVED', 'Extent?', 'ref', 'serveridneventid,serverid', 'serveridneventid', '109', '', '45', 'Using where'
Run Code Online (Sandbox Code Playgroud)

一个班轮

'1', 'SIMPLE', 'network', 'ref', 'serveridneventid,serverid', 'serveridneventid', '109', 'const', '45', 'Using where; Using filesort'
Run Code Online (Sandbox Code Playgroud)

这来自我的QA环境,因此我上面粘贴的时间与rowcount explain语句无关.我认为有大约500,000条记录匹配一个服务器ID.

我从MySQL切换到SQL Server.我不想最终完全重写应用程序层.

Pet*_*eGO 7

这是从表达式树逻辑构建查询的最简单方法.通常表现不会成为问题.如果您遇到性能问题,可以尝试这样的方法来恢复实体:

var results = db.ExecuteStoreQuery<Network>(
    "SELECT Id, ServerID, EventId, StartTime FROM Network WHERE ServerID = @ID", 
    serverId);

results = results.OrderBy(x=> x.StartTime).Take(limit);
Run Code Online (Sandbox Code Playgroud)

  • 我打赌这不会发生在SQL Server中;)我想知道他们的执行计划构建例程是如何不同的.我要去尝试再现. (2认同)
  • 我对此也很好奇但是懒得自己做研究:) (2认同)