这是我需要转换为 LINQ 语句以在我的 ASP.NET MVC 3 项目中使用的查询。我对 LINQ 还不是很好,所以我需要一些帮助。
WITH CTE AS (
SELECT a.GalleryID GalleryID_A, a.GalleryTitle, a.GalleryDate, b.*
,ROW_NUMBER() OVER (PARTITION BY a.GalleryID, a.GalleryTitle, a.GalleryDate
ORDER BY b.MediaThumb DESC) AS Rn
FROM Media b
INNER JOIN Galleries A ON a.GalleryID = b.GalleryID
),
CTE2 AS (
SELECT a.GalleryID GalleryID_A, a.GalleryTitle, a.GalleryDate, b.*, 1 Rn
FROM Media b
LEFT OUTER JOIN Galleries A ON a.GalleryID = b.GalleryID
)
SELECT * FROM CTE where rn = 1
UNION ALL
SELECT * FROM CTE2
WHERE rn = 1
AND galleryid is null
ORDER BY MediaID DESC
这是我的解决方案。
var Results = DB.Database.SqlQuery<WhatsNew>
(@" WITH CTE AS (
SELECT a.GalleryTitle, a.GalleryDate, b.*,
ROW_NUMBER() OVER (PARTITION BY a.GalleryID, a.GalleryTitle, a.GalleryDate
ORDER BY b.MediaThumb DESC) AS Rn
FROM Media b
INNER JOIN Galleries A
ON a.GalleryID = b.GalleryID
),
CTE2 AS
(
SELECT a.GalleryTitle, a.GalleryDate, b.*,
1 Rn
FROM Media b
LEFT OUTER JOIN Galleries A
ON a.GalleryID = b.GalleryID
)
SELECT * FROM CTE where rn = 1
UNION ALL
SELECT * FROM CTE2 WHERE rn = 1 and galleryid is null
ORDER BY MediaID DESC ");