将 SQL 转换为 LINQ 的问题

Issues in converting SQL to LINQ

我有一个如下所示的 sql 查询(table 和列名是任意的,为了提问):

select t3.MRIID as 'Ids'
from table1 t1  
    join table2 t2 with (nolock) on t1.ID = t2.SPID
    join table3 t3 with (nolock) on t2.ID = t3.SPMRID
    join table4 t4 on t4.MRID = t3.MRID
where 
    t3.MRISID = 18
    and t1.ID = 315
group by t3.MRIID
having SUM(CAST(t4.IRGPC AS INT)) > 0  

我正在尝试将其转换为等效的 LINQ 查询,这就是我目前所拥有的。当我在 LINQPad 中 运行 它并想知道是否有人对我出错的地方有解释时,这并没有给我预期的结果?我知道我的 group/having 条款是这里的问题,但不确定如何解决它。

from t1 in table1
    join t2 in table2 on t1.ID equals t2.SPID
    join t3 in table3 on t2.ID equals t3.SPMRID
    join t4 in table4 on t3.MRID equals t4.ID
where t3.MRISID == 18 && t1.ID == 315
group new { t1, t2, t3, t4 } by t3.MRID into groupedResult
let count = groupedResult.Count()
where count > 0
select new { Something = groupedResult.Key}

SQL 查询在结果中给出了 2 'Ids',这是预期的结果,而 Linq 查询给出了 3 个结果,其中 1 'Id' 与 [=15= 不匹配] 条款

不胜感激!

[更新] 我刚刚注意到我在 sql 查询中的 having 子句不是 Linq 中的等效子句,我想了解如何实现它?

根据 Mrinal 的解决方案(和聊天评论),我的 LINQ 现在处于

from t1 in table1
    join t2 in table2 on t1.ID equals t2.SPID
    join t3 in table3 on t2.ID equals t3.SPMRID
    join t4 in table4 on t3.MRID equals t4.ID
where t3.MRISID == 18 && t1.ID == 315
group Convert.ToInt32(cd.IRGPC) by mriw.MRIID into groupedResult
where groupedResult.Sum() > 0
select new { groupedResult.Key}

然而,这仍然与原始 SQL 语句给出的结果不匹配。我通过 LinqPad 运行 这个 linq 查询来查看生成的 SQL 它看起来像下面。

-- Region Parameters
DECLARE @p0 Int = 18
DECLARE @p1 Int = 315
DECLARE @p2 Int = 0
-- EndRegion
SELECT [t5].[MRIID] AS [Key]
FROM (
    SELECT SUM([t4].[value]) AS [value], [t4].[MRIID]
    FROM (
        SELECT CONVERT(Int,[t3].[IRGPC]) AS [value], [t2].[MRISID], [t0].[ID], [t2].[MRIID]
        FROM [table1] AS [t0]
        INNER JOIN [table2] AS [t1] ON [t0].[ID] = [t1].[SPID]
        INNER JOIN [table3] AS [t2] ON [t1].[ID] = [t2].[SPMRID]
        INNER JOIN [table4] AS [t3] ON [t2].[MRIID] = [t3].[ID]
        ) AS [t4]
    WHERE ([t4].[MRISID] = @p0) AND ([t4].[ID] = @p1)
    GROUP BY [t4].[MRIID]
    ) AS [t5]
WHERE [t5].[value] > @p2

如果这个额外的细节有帮助,IRGPC 列是 SQL 中的 bit 类型和 C# 代码中的 bool 类型。

有什么建议吗?

而不是

let count = groupedResult.Count()
where count > 0

使用 where 子句

where groupedResult.Sum(x => x.t4.IRGPC) > 0

尝试按如下方式修改 Linq 查询:

from t1 in table1
join t2 in table2 on t1.ID equals t2.SPID
join t3 in table3 on t2.ID equals t3.SPMRID
join t4 in table4 on t3.MRID equals t4.ID
where t3.MRISID == 18 && t1.ID == 315
group new { t1, t2, t3, t4 } by t3.MRID into groupedResult
where groupedResult.Sum(y => (int)y.t4.IRGPC) > 0
select new { Something = groupedResult.Key }

修改:

groupedResult.Count() > 0 更改为 groupedResult.Sum(y => (int)y.t4.IRGPC) > 0,因为在 Sql 查询中您有 having SUM(CAST(t4.IRGPC AS INT)) > 0,需要在 Linq 查询中复制

编辑 1:

正如 OP 所提到的,t4.IRGPC 是一种布尔类型,用例是获得一个至少有一个值为 true 的分组,请尝试以下选项:

group t4.IRGPC by t3.MRID into groupedResult
where groupedResult.Any(x => x)