我试试Dapper ORM。我可以使用以下代码查询表中的数据:
Dim comments As List(Of Comment)
Using conn = New SqlConnection(ConnectionString)
conn.Open()
comments = conn.Query(Of Comment)("SELECT * from comments where userid = @commentid", New With {.userid= 1})
End Using
Return View(comments)
我有兴趣学习如何使用Dapper进行分页/排序。 EF有“跳过”和“接受”来帮助解决这个问题。我知道微型ORM没有内置但想知道实现这一目标的最佳方法。
答案 0 :(得分:19)
如果你想跳过并使用Dapper,you do it with T-SQL。
SELECT *
FROM
(
SELECT tbl.*, ROW_NUMBER() OVER (ORDER BY ID) rownum
FROM comments as tbl
) seq
WHERE seq.rownum BETWEEN @x AND @y
AND userid = @commentid
ORDER BY seq.rownum
答案 1 :(得分:0)
你现在可以做到。
您需要做的就是编写一个带有Query和PageSize和PageNumber的扩展方法,然后你需要附加
OFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;
行查询并执行。
请注意,查询绝对需要ORDER-BY子句(至少在T-SQL中)
这适用于MS-SQL(2012+),PostgreSQL(8.4+)和Oracle(12c +)
对于MySQL,你必须附加LIMIT offset,page_size。
LIMIT @PageSize * (@PageNumber - 1), @PageSize
对于Firebird,你必须追加ROWS x到y
ROWS (@PageSize * (@PageNumber - 1)) TO (@PageSize * @PageNumber -1)
对于base-1索引,它将从startoffset_base1到endoffset_base1
StartAt @PageSize * (pagenum - 1) + 1 EndAt @PageSize * (pagenum - 1) + @PageSize
示例:强>
DECLARE @PageSize int
DECLARE @PageNumber int
SET @PageSize = 5
SET @PageNumber = 2
SELECT * FROM T_Users
ORDER BY USR_ID
-- Must contain "ORDER BY"
OFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;
有关各种不同RDBMS的语法,请参见
http://www.jooq.org/doc/3.5/manual/sql-building/sql-statements/select-statement/limit-clause/
验证
DECLARE @PageSize int
SET @PageSize = 5
;WITH CTE AS
(
SELECT 1 as pagenum
UNION ALL
SELECT pagenum+1 AS pagenum
FROM CTE
WHERE CTE.pagenum < 100
)
SELECT
pagenum
,@PageSize * (pagenum - 1) AS StartOFFSETBase0
--,@PageSize * (pagenum - 1) + @PageSize - 1 AS EndOFFSETBase0
,@PageSize * pagenum - 1 AS EndOFFSETBase0 -- Simplified
,@PageSize * (pagenum - 1) + 1 AS StartOFFSETBase1
,@PageSize * (pagenum - 1) + @PageSize AS EndOFFSETBase1
FROM CTE