Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Dapper QueryMultipleAsync use offset to could not return pagedlist

Open Cuiqs76 opened this issue 6 years ago • 2 comments

I use Dapper QueryMultipleAsync to read multi records.

using (var cn = new SqlConnection(_connectionString))
            {
                cn.Open();
                var sql = @"Select Count(1) From RepairReport;
                     Select r.Id, r.RepairDate,m.Name as Repairman,r.FromDepartment,r.OccurAt, r.RmaNo,
                     r.ParentProductCode,r.ParentProductName, r.ParentProductModel,r.ParentProductSerialNo, r.ParentProductManufactureDate,
                     r.FaultPartCode, r.FaultPartName, r.FaultPartModel, r.FaultPartSerialNo,r.FaultPartManufactureDate, r.FaultDescription
                     From RepairReport r
                     Left Join
                     Repairman m
                     On r.RepairmanId = m.Id
                     Order By r.Id";
               

                var list =await Query.GetPageListAsync<RepairReportItemDto>(cn, sql, request.PageIndex, request.PageSize);

                return list;
            }

public static async Task<PagedList<T>> GetPageListAsync<T>(IDbConnection conn, string sql, int pageIndex, int pageSize)
        {
         
           // var sql1 = $@"Select Count(1) From {tableName};";
            var query = $@"{sql} OFFSET {(pageIndex - 1) * pageSize} ROWS FETCH NEXT {pageSize} ROWS ONLY;";

            using (var reader = await conn.QueryMultipleAsync(sql))
            {
                int total = await reader.ReadFirstAsync<int>();
                return new PagedList<T>()
                {
                    Items = await reader.ReadAsync<T>(),
                    ItemCount = total,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                };
            }
        }

but the Items always return all records. the same sql i use mssms to run return right results.

Cuiqs76 avatar Mar 31 '20 09:03 Cuiqs76

using (var reader = await conn.QueryMultipleAsync(sql))

You probably intended to use query instead of sql here? also, note that you can use a special dapper syntax to make this more efficient; in Dapper, if it sees the token {=foo}, this works like @foo but instead of using a parameter, it adds the literal value from the parameters (foo must still exist in the parameters), as long as it is an integer etc (to avoid injection problems) - this helps Dapper avoid saturating it's internal cache of queries.

mgravell avatar Mar 31 '20 09:03 mgravell

note also: OFFSET and FETCH NEXT can be parameterized - no need to put the values into the command

mgravell avatar Apr 01 '20 09:04 mgravell