Linq加入Group By

时间:2012-09-29 02:06:07

标签: c# linq entity-framework

好的,我正在尝试将以下SQL查询复制到Linq表达式中:

SELECT
    I.EmployeeNumber,
    E.TITLE,
    E.FNAM, 
    E.LNAM
FROM
    Incidents I INNER JOIN Employees E ON I.IncidentEmployee = E.EmployeeNumber
GROUP BY
    I.EmployeeNumber,
    E.TITLE,
    E.FNAM, 
    E.LNAM

足够简单(或者至少我认为):

var query = (from e in contextDB.Employees
              join i in contextDB.Incidents on i.IncidentEmployee = e.EmployeeNumber
              group e by new { i.IncidentEmployee, e.TITLE, e.FNAM, e.LNAM } into allIncEmps
              select new
                          {
                              IncEmpNum = allIncEmps.Key.IncidentEmployee
                              TITLE = allIncEmps.Key.TITLE,
                              USERFNAM = allIncEmps.Key.FNAM,
                              USERLNAM = allIncEmps.Key.LNAM
                          });

但是我没有收到我所表达的结果,所以我启动SQL Profiler以查看从管道发送到SQL Server的内容,这就是我所看到的:

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM ( SELECT DISTINCT 
        [Extent2].[IncidentEmployee] AS [IncidentEmployee], 
        [Extent1].[TITLE] AS [TITLE], 
        [Extent1].[FNAM] AS [FNAM], 
        [Extent1].[LNAM] AS [LNAM]
        FROM  [dbo].[Employees] AS [Extent1]
        INNER JOIN [dbo].[INCIDENTS] AS [Extent2] ON ([Extent1].[EmployeeNumber] = [Extent2].[IncidentEmployee]) OR (([Extent1].[EmployeeNumber] IS NULL) AND ([Extent2].[IncidentEmployee] IS NULL))
    )  AS [Distinct1]
)  AS [GroupBy1]

正如您从发送到SQL Server的SQL字符串中可以看到的那样,我期望返回的字段都没有包含在Select子句中。我做错了什么?

更新

这是一个非常漫长的一天,我再次重新运行代码,现在这是从管道发送的SQL:

SELECT 
[Distinct1].[IncidentEmployee] AS [IncidentEmployee], 
[Distinct1].[TITLE] AS [TITLE], 
[Distinct1].[FNAM] AS [FNAM], 
[Distinct1].[LNAM] AS [LNAM]
FROM ( SELECT DISTINCT 
    [Extent1].[OFFNUM] AS [OFFNUM], 
    [Extent1].[TITLE] AS [TITLE], 
    [Extent1].[FNAM] AS [FNAM], 
    [Extent1].[LNAM] AS [LNAM]
    FROM  [dbo].[Employees] AS [Extent1]
    INNER JOIN [dbo].[INCIDENTS] AS [Extent2] ON ([Extent1].[EmployeeNumber] = [Extent2].[IncidentEmployee]) OR (([Extent1].[EmployeeNumber] IS NULL) AND ([Extent2].[IncidentEmployee] IS NULL))
)  AS [Distinct1]

但是当我尝试循环记录集时,我仍然没有看到结果

foreach (var emps in query)
{

}

1 个答案:

答案 0 :(得分:1)

不确定为什么查询不会返回它应该返回的内容,但是我发现,因为您只查询组键而不是任何分组结果,所以除了Distinct()之外什么都没有:

var query =
(from e in contextDB.Employees
 join i in contextDB.Incidents on i.IncidentEmployee equals e.EmployeeNumber
 select new
 {
     IncEmpNum = i.IncidentEmployee
     TITLE = e.TITLE,
     USERFNAM = e.FNAM,
     USERLNAM = e.LNAM
 }).Distinct();

但EF足够聪明,也可以看到这个,并创建了一个DISTINCT查询。

您没有指定您期望的结果以及实际结果的不同之处,但我真的看不出分组如何产生与Distinct不同的结果。

但你的代码是如何编译的?正如xeondev所注意到的:在连接语句中应该有equals而不是=。我的编译器(:D)不会吞下它。生成的SQL连接也很奇怪:它还匹配两个连接值都为NULL的记录。这使我怀疑至少有一个密钥(i.IncidentEmployeee.EmployeeNumber)可以为空,您应该使用i.IncidentEmployee.Valuee.EmployeeNumber.Value或两者都使用。