0

这是我需要转换为 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 ");
4

3 回答 3

1

如果您只是学习 linq 并想转换这样的复杂查询,我建议您使用此工具

http://www.sqltolinq.com/

于 2012-08-25T04:26:36.187 回答
1

在 sql 中将查询创建为视图,说“MyView”,然后从 MVC 项目中调用它。

return db.ExecuteStoreQuery<YourEntityType>("SELECT * FROM MyView");
于 2012-08-25T21:31:06.977 回答
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);
于 2012-08-27T18:12:16.673 回答