我需要将此SQL查询转换为LINQ,以便我可以在我的项目中使用它

时间:2012-07-11 20:10:49

标签: c# linq entity-framework linq-to-entities group-by

stackoverflow中的某个人最近帮我构建了这个sql查询来返回我正在寻找的数据。

我需要将它转换为LINQ语句,以便我可以在ASP.NET MVC3 C#项目中使用它。

谢谢!

SELECT TOP 4 a.GalleryID, a.GalleryTitle, a.GalleryDate, MAX(b.MediaThumb) AS MediaThumb
FROM Galleries a
INNER JOIN Media b
ON a.GalleryID = b.GalleryID
GROUP BY a.GalleryID, a.GalleryTitle, a.GalleryDate
ORDER BY a.GalleryID desc

3 个答案:

答案 0 :(得分:2)

编辑:这是一个根据给定的T-Sql进行分组的版本:

var Results = (from g in DB.Galleries
               join m in DB.Media
               on g.GalleryID equals m.GalleryID
               group m by new { g.GalleryID, g.GalleryTitle, g.GalleryDate } into grp
               orderby grp.Key.GalleryID descending
               select new LatestGalleries
               {
                   GalleryID = grp.Key.GalleryID,
                   GalleryTitle = grp.Key.GalleryTitle,
                   GalleryDate = grp.Key.GalleryDate,
                   MediaThumb = grp.FirstOrDefault().MediaThumb
               });

答案 1 :(得分:1)

这样的事情应该有效:

(
  from a in galleries
  join b in media on b.GalleryID equals a.GalleryID
  group by new {a.GalleryID, a.GalleryTitle, a.GalleryDate} into grouping
  order by grouping.Key.GalleryID
  select new {grouping.Key.GalleryID, grouping.Key.GalleryTitle, grouping.Key.GalleryDate, grouping.Max(x=>x.MediaThumb)}
).Take(4)

答案 2 :(得分:0)

您需要首先在Media上配置EF Navigation Property,然后:

var q = (from a in db.Galleries
        group a by new { a.GalleryID, a.GalleryTitle, a.GalleryDate } into g
        orderby g.Key.GalleryID descending
        select new
        {
            GalleryID = g.Key.GalleryID,
            GalleryTitle = g.Key.GalleryTitle,
            GalleryDate = g.Key.GalleryDate,
            MediaThumb = g.Max(a => a.Media) // Gallery.Media is a navigation property
        }).Take(4);