实体框架:无理由地查询执行'select from'

时间:2010-02-11 01:36:21

标签: entity-framework

我遇到了实体框架的一些问题。我正在从数据库中的视图执行一个简单的选择。但是,当我查看EF生成的SQL时,它使用select from执行查询两次。这是它应该运作的方式吗?这似乎非常低效。

var reads = (from rt in ctx.C2kReadsToTransfer
                     where rt.ReadDt > fromDate
                     && rt.ReadDt < toDate
                     select rt);

这会转换为以下SQL

SELECT 

 [Extent1].[AMRID] AS [AMRID]
 , [Extent1].[Comments] AS [Comments]
 , [Extent1].[ExternalSystemType] AS [ExternalSystemType]
 , [Extent1].[LastReadDt] AS [LastReadDt]
 , [Extent1].[ReadDt] AS [ReadDt]
 , [Extent1].[Reading] AS [Reading]
 , [Extent1].[Units] AS [Units]
 , [Extent1].[Transferred] AS [Transferred]



 FROM 
     (SELECT 
      [ReadsToTransfer].[AMRID] AS [AMRID]
      , [ReadsToTransfer].[Comments] AS [Comments]
      , [ReadsToTransfer].[ExternalSystemType] AS [ExternalSystemType]
      , [ReadsToTransfer].[LastReadDt] AS [LastReadDt]
      , [ReadsToTransfer].[ReadDt] AS [ReadDt]
      , [ReadsToTransfer].[Reading] AS [Reading]
      , [ReadsToTransfer].[Transferred] AS [Transferred]
      , [ReadsToTransfer].[Units] AS [Units]
      FROM [dbo].[ReadsToTransfer] AS [ReadsToTransfer])
    AS [Extent1]

这似乎是非常低效的,特别是当表包含与我们的行相近的2.5亿行时。此外,如果我将.Take(2000)添加到代码的末尾,它只是在第一个选择上放置一个'select top 2000'。因此,让它选择内部选择的前2000,这是整个表。

对此有何想法?

1 个答案:

答案 0 :(得分:2)

  

这似乎效率很低

我不这么认为......外部的SELECT只是内部SELECT的一个投影(实际上是一个标识投影),投影对性能影响可以忽略不计......

关于TOP 2000子句,它在外部SELECT上的事实并不意味着DB将从内部SELECT读取所有行;只要外部SELECT请求它们就会读取它们,然后停止。

尝试手动运行查询,有或没有外部SELECT:我打赌你不会发现性能有任何显着差异。