-1

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
4

3 回答 3

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
               });
于 2012-07-11T20:16:36.233 回答
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)
于 2012-07-11T20:17:22.637 回答
0

您需要先在 Media 上配置 EF导航属性,然后:

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);
于 2012-07-11T20:21:58.720 回答