需要帮助将SQL左连接查询转换为LINQ格式

本文关键字:转换 查询 LINQ 格式 连接 帮助 SQL | 更新日期: 2023-09-27 17:54:27

我是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

需要帮助将SQL左连接查询转换为LINQ格式

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
};
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
             };

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

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();