为什么Linq2EF Join生成完整的外连接?

时间:2012-06-27 18:44:42

标签: linq entity-framework linq-to-entities odp.net

我在EF 4.3.1中使用了一些简单的LINQ:

Dim Results = (
    From T1 In Context.Table1
    Where T1.IDColumn = 1568
    Join T2 In Context.Table2 On T1.IDColumn Equals T2.IDColumn
    Select New With {
        .Quantity = T1.Quantity
    })

不幸的是,当我运行它时,它需要永远。我已经将问题跟踪到了生成的SQL的一个完全不必要的部分。生成的SQL如下所示:

SELECT   1 AS "C1"
        ,CAST( "Extent2"."Quantity" AS number(19,0)) AS "C2"  
FROM  [table1] "Extent1"  
INNER JOIN [table2] "Extent2" ON 
(
  ( 
    CAST( "Extent1"."IDColumn" AS number(19,0))
  ) = (
    CAST( "Extent2"."IDColumn" AS number(19,0))
  )
) 
OR 
(
  ( 
    CAST( "Extent1"."IDColumn" AS number(19,0)) IS NULL
  ) 
  AND 
  ( 
    CAST( "Extent2"."IDColumn" AS number(19,0)) IS NULL
  )
)  
WHERE 
(
  1568 = ( 
    CAST( "Extent1"."ForeginKey" AS number(19,0))
  )
)

此查询大约需要13秒才能执行。如果我删除OR / NULL块,它会下降到0.122秒:

    SELECT   1 AS "C1"
            ,CAST( "Extent2"."Quantity" AS number(19,0)) AS "C2"  
    FROM  [table1] "Extent1"  
    INNER JOIN [table2] "Extent2" ON 
    (
      ( 
        CAST( "Extent1"."IDColumn" AS number(19,0))
      ) = (
        CAST( "Extent2"."IDColumn" AS number(19,0))
      )
    ) 
    WHERE 
    (
      1568 = ( 
        CAST( "Extent1"."ForeginKey" AS number(19,0))
      )
    )

有人建议如何让linq查询不生成(不需要的)空检查?

1 个答案:

答案 0 :(得分:0)

根据Microsoft的Data Type map,将要比较的列的数据类型从Int64更改为Decimal,并且查询和性能得到显着改善。感谢Jon Skeet让我走上了正确的道路。