PetaPoco 分页查询生成改进

本文关键字:分页 查询 PetaPoco | 更新日期: 2023-09-27 18:32:32

我是PetaPoco的忠实粉丝,当我看到其中编写的代码时,我感到非常惊讶。但是,在将其用于现实生活中的项目时,我遇到了一个问题,其中我有一个如下所示的查询:

SELECT  em.SysEmailID, 
        [DisplayID], 
         Case When em.SysEmailCategoryID IS NULL Then em.CategoryName Else cat.CategoryName End as 'ResultCategoryName',
         [Name], 
         IsActive, 
         em.ModifiedDateTime, 
         us.Username  
            FROM [dbo].[SysEmail] em 
                Left JOIN dbo.Users us ON em.CreatedBy = us.UserID  
                    Left JOIN dbo.SysEmailCategory cat on em.SysEmailCategoryID = cat.SysEmailCategoryID 

ResultCategoryName 是使用Case When语句在"动态"上生成的。这是一个相当简单的查询。现在,如果您注意到用 PetaPoco 编写的代码,您将看到它包装了您的语句并附加了行号函数。因此,您的查询将变为:

SELECT * FROM 
    (
        SELECT ROW_NUMBER() OVER (ORDER BY ResultCategoryName desc) peta_rn,
         em.SysEmailID, 
         [DisplayID], 
         Case When em.SysEmailCategoryID IS NULL Then em.CategoryName Else cat.CategoryName End as 
         'ResultCategoryName',
         [Name], 
         IsActive, 
         em.ModifiedDateTime, 
         us.Username  
            FROM [dbo].[SysEmail] em Left JOIN dbo.Users us ON em.CreatedBy = us.UserID  
                Left JOIN dbo.SysEmailCategory cat on em.SysEmailCategoryID = cat.SysEmailCategoryID 
     ) peta_paged WHERE peta_rn>0 AND peta_rn<=10

发生这种情况时,您会收到 Sql 错误Invalid column name"结果类别名称"。我'BuildPageQueries<T>'修改了该方法,并在生成实际 SQL 的if (_dbType == DBType.SqlServer || _dbType == DBType.Oracle)内将其修改为如下所示:

 sqlPage = string.Format("SELECT * FROM (SELECT ROW_NUMBER() OVER ({0}) peta_rn, peta_query.* From (Select {1}) as peta_query) peta_paged WHERE peta_rn>@{2} AND peta_rn<=@{3}",
                                        sqlOrderBy == null ? "ORDER BY (SELECT NULL)" : sqlOrderBy, sqlSelectRemoved, args.Length, args.Length + 1);

这生成了查询:

SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY ResultCategoryName asc) peta_rn, 
    peta_query.* 
        From (
                Select em.SysEmailID, [DisplayID], 
                Case When em.SysEmailCategoryID IS NULL Then em.CategoryName Else cat.CategoryName End as 'ResultCategoryName',
                [Name], 
                IsActive, 
                em.ModifiedDateTime, 
                us.Username  
                    FROM [dbo].[SysEmail] em Left JOIN dbo.Users us ON em.CreatedBy = us.UserID  
                        Left JOIN dbo.SysEmailCategory cat on em.SysEmailCategoryID = cat.SysEmailCategoryID 
                            ) as peta_query) peta_paged WHERE peta_rn>0 AND peta_rn<=10

这行得通!! :)。但是,我需要知道这是否是正确的方法,或者是否有更好的方法可以做到这一点。

PetaPoco 分页查询生成改进

您所要做的就是用另一个选择包装您的 sql。

例如。

select * from (**your query here**) query order by ResultCategoryName asc

仅当具有计算列时才需要执行此操作。