【问题标题】:Having Trouble Converting SQL to LINQ when using a join on a select statement在选择语句上使用联接时无法将 SQL 转换为 LINQ
【发布时间】:2016-12-02 13:24:23
【问题描述】:

伙计们,

尝试将以下 SQL-Server 命令转换为 LINQ。我已经通过 SSMS 验证了 SQL 是否正确运行。

select top 100 tts.* from tblLCState tts
INNER JOIN
    (SELECT fldLCID, MAX(fldStateDate) AS Statedate
    FROM tblLCState
    GROUP BY fldLCID) grptts 
ON tts.fldLCID = grptts.fldLCID 
AND tts.fldStateDate = grptts.Statedate
where fldLCStateCode = 1
order by fldStateDate desc

我很困惑如何将表 tblLCState 加入到 select 语句中。我对 LNIQ 的尝试如下:

from tRow in tblLCState
join irow2 in (from iRow in tblLCState
    group iRow by iRow.fldLCID into g
    select new {fldLCID = g.Key, MaxStateDate =  (from t2 in g select t2.fldStateDate).Max()} ) 
on ((tRow.fldStateDate = irow2.MaxStateDate) and (tRow.fldLCID = irow2.g.fldLCID))

错误出现在 on 子句中的 and 运算符上,表明 a ) 是预期的。在这一点上,我还没有尝试过 where/order/top 100。只是花了很多时间寻找这种形式或任何其他形式没有运气的加入。我在另一张桌子上看到了很多要加入的帖子,但不幸的是我没有这种奢侈。

任何帮助将不胜感激。

谢谢

汤姆·D.

【问题讨论】:

  • 在C#中你需要使用&&而不是and

标签: c# sql-server linq join


【解决方案1】:

LINQ

  var result = (from tRow in tblLCState
                join irow2 in (from iRow in tblLCState
                                group iRow by iRow.fldLCID into g
                                select new { fldLCID = g.Key, MaxStateDate = g.Max(k => k.fldStateDate) })
                on new { StateDate = tRow.fldStateDate, tRow.fldLCID } equals new { StateDate = irow2.MaxStateDate, irow2.fldLCID }
                select tRow);

【讨论】:

  • Selami .....这在我的 linqpad 中运行良好(除了需要删除最后一行中的 .g.)但是当我将它放入我的 C# 代码时出现错误.它出现编译错误:错误 CS1936 找不到源类型“tblLCState”的查询模式的实现。未找到“GroupBy”。我已经验证我的代码中有正确的 using 指令。关于我没有看到的任何想法??
  • @TomD 确保 System.Data.Linq 引用包含在项目中。
  • @salami 验证了该引用已包含在项目中。所有其他 linq 代码都在工作。
  • @salami 发现了我的错误,它在代码和 linqpad 上运行良好。感谢您的帮助
猜你喜欢
  • 2013-02-15
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多