这是我需要转换为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 ");
答案 0 :(得分:1)
如果您只是在学习linq并希望转换这样的复杂查询,我建议您使用此工具
答案 1 :(得分:1)
在sql中创建您的查询视图,说“MyView”,然后从您的MVC项目中调用它。
return db.ExecuteStoreQuery<YourEntityType>("SELECT * FROM MyView");
答案 2 :(得分:0)
如果您仅将CTE用于分页,则可以使用Skip()
和Take()
扩展名。
var page = (from a in _context.Set<Media>()
orderby a.GalleryID, a.GalleryTitle, a.GalleryDate
select a)
.Skip(page * size).Take(size);
或使用PagedList。
var page = (from a in _context.Set<Media>()
orderby a.GalleryID, a.GalleryTitle, a.GalleryDate
select a)
.ToPagedList(page, size);