我是 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
我是 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
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 = 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();
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
};