我是LINQ的新手,但語法尚不完善。有人可以幫助我將這個SQL查詢轉換爲一個LINQ語句,供我的C#項目使用。需要幫助將SQL左連接查詢轉換爲LINQ格式
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#項目使用。需要幫助將SQL左連接查詢轉換爲LINQ格式
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
};
謝謝!這使我朝着正確的方向前進。 – Maddhacker24
我不能現在就測試它,但它應該是這樣的:
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();
你失去了'GalleryTitles'。 –
你是對的,修好了,謝謝 –
但它不是左連接。 –
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
};
http://msdn.microsoft.com/en-us /library/vstudio/bb397895(v=vs.100).aspx – user959729
您必須爲具體查詢顯示您的實體對象模型。 –