This is the query I need to convert to a LINQ statement for use inside my ASP.NET MVC 3 project. I'm not all that good with LINQ yet so I'm going to need some help please.
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
This was my solution.
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 ");
if you are just learning linq and want to convert a complicated query like this I would recommend using this tool
创建查询作为sql视图,说“ MyView”,然后从MVC项目中调用它。
return db.ExecuteStoreQuery<YourEntityType>("SELECT * FROM MyView");
If you're using CTEs only for paging, you can use the Skip()
and Take()
extensions.
var page = (from a in _context.Set<Media>()
orderby a.GalleryID, a.GalleryTitle, a.GalleryDate
select a)
.Skip(page * size).Take(size);
Or use PagedList .
var page = (from a in _context.Set<Media>()
orderby a.GalleryID, a.GalleryTitle, a.GalleryDate
select a)
.ToPagedList(page, size);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.