0

我是 LINQ 的新手,语法还不是很好。有人可以帮我将此 SQL 查询转换为 LINQ 语句,以便在我的 C# 项目中使用。

SELECT g.GalleryTitle, m.*
FROM Media AS m LEFT JOIN Galleries AS g ON m.GalleryID = g.GalleryID
WHERE m.MediaDate >= GETDATE() - 30
ORDER BY m.Views DESC
4

3 回答 3

2
from m in Db.Media
join g in Db.Galleries on m.GalleryID equals g.GalleryID into MediaGalleries
from mg in MediaGalleries.DefaultIfEmpty()
where m.MediaDate >= DateTime.Today.AddDays(-30)
orderby m.Views descending
select new
{
    GalleryTitle = mg != null ? mg.GalleryTitle : null,
    Media = m
};
于 2013-01-17T17:32:08.770 回答
0

我现在无法测试它,但它应该是这样的:

var result = Media.GroupJoin(Galleries, m => m.GalleryID, g => g.GalleryID, 
                    (m, g) => new {m, g})
                  .SelectMany(mg => mg.g.DefaultIfEmpty(), 
                    (m,g) => new { Media = m.m, GalleryTitle = g != null ? g.GalleryTitle : default(string) })
                  .OrderByDescending(m => m.Media.Views).ToList();
于 2013-01-17T17:29:03.293 回答
0
var result = from m in Media

             join g in Galleries
               on m.GalleryId equals g.GalleryId
             into gJoinData
             from gJoinRecord in gJoinData.DefaultIfEmpty( )

             where m.MediaDate.CompareTo( DateTime.Today.AddDays( -30.0 ) ) >= 0
             orderby m.Views descending

             select new
             {
                 M_Record = m,
                 GalleryTitle = gJoinRecord.GalleryTitle
             };
于 2013-01-17T17:31:45.820 回答