如何让以下T-SQL在LINQ中工作

时间:2013-06-06 15:40:05

标签: sql-server linq entity-framework

我正在尝试将以下查询转换为LINQ语句:

SELECT
    TOP 10
      S.Id
    , S.Url
    , S.Score
    , MAX(LastUpdated) AS LastUpdated
FROM
    Sites S
    LEFT JOIN History H ON S.ID = H.SiteId
WHERE
    S.Active = 1 AND Approved = 1
GROUP BY
      S.Id
    , S.Url
    , S.Score
ORDER BY LastUpdated

请帮助!

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

var result = (
    from s in Sites
    join h in History
        on s.ID equals h.SiteID into left1
    from left2 in left1.DefaultIfEmpty()
    where s.Active == true && left2.Approved == true
    group left2 by new {s.ID, s.Url, s.Score} into grouped
    orderby grouped.Max(h => h.LastUpdated)
    select new
    {
        SiteID = grouped.Key.ID,
        Url = grouped.Key.Url,
        Score = grouped.Key.Score,
        LastUpdated = grouped.Max(h => h.LastUpdated)
    })
    .Take(10);

无论如何,当我在LINQPad中进行测试时,它仍然有效。