EF6 - 生成不需要的嵌套查询

时间:2015-06-04 16:50:15

标签: sql-server linq entity-framework

我有以下表格:

MAIN_TBL:
Col1 | Col2 | Col3
------------------
A    | B    | C
D    | E    | F

REF_TBL:
Ref1 | Ref2 | Ref3
------------------
A    | G1   | Foo
D    | G1   | Bar
Q    | G2   | Xyz

我希望编写以下SQL查询:

SELECT    M.Col1
FROM      MAIN_TBL M
LEFT JOIN REF_TBL R
ON        R.Ref1 = M.Col1 
AND       R.Ref2 = 'G1'
WHERE     M.Col3 = 'C'

我编写了以下LINQ查询:

from main in dbContext.MAIN_TBL
join refr in dbContext.REF_TBL
on "G1" equals refr.Ref2
into refrLookup
from refr in refrLookup.DefaultIfEmpty()
where main.Col1 == refr.Col1
select main.Col1

生成的SQL是:

SELECT 
    [MAIN_TBL].[Col1]
    FROM  (SELECT 
    [MAIN_TBL].[Col1] AS [Col1],
    [MAIN_TBL].[Col2] AS [Col2],
    [MAIN_TBL].[Col3] AS [Col3]
    FROM [MAIN_TBL]) AS [Extent1]
    INNER JOIN (SELECT 
    [REF_TBL].[Ref1] AS [Ref1],
    [REF_TBL].[Ref2] AS [Ref2],
    [REF_TBL].[Ref3] AS [Ref3]
    FROM [REF_TBL]) AS [Extent2] ON [Extent1].[Col1] = [Extent2].[Ref1]
    WHERE ('G1' = [Extent2].[DESCRIPTION]) AND ([Extent2].[Ref1] IS NOT NULL) AND CAST( [Extent1].[Col3] AS VARCHAR) = 'C') ...

看起来它正在另一个查询中嵌套查询,而我只是希望它从表中提取。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我可能错了,但看起来你在linq查询和sql查询中都没有做同样的事情,特别是你的左连接子句。

如果你想要类似于你的SQL查询,我会选择这个。

from main in dbContext.MAIN_TBL.Where(x => x.Col3 == "C")
join refr in dbContext.REF_TBL
on new{n = "G1", c = main.Col1} equals new{n = refr.Ref2, c = refr.Col1}
   into refrLookup
from r2 in refrLookup.DefaultIfEmpty()
select main.Col1

顺便说一下,在select子句中不存在的表上保持连接没有多大意义:如果有多个相关项目,你将获得多个相同的Col1左边加入了桌子......