locked
SqlException error when trying to implement pagination in .net core web api RRS feed

  • Question

  • User835255308 posted

    Hello All,

    I have these two pieces of code to implement pagination in .net core.

    The first piece is a class as follows:

    public class QueryParameters
    {
        const int _maxSize = 100;
        private int _size = 50;
    
        public int Page { get; set; }
    
        public int Size 
        {  
            get { return _size; }
            set { _size = Math.Min(_maxSize, value); }
        }
    }

    The second one is my HttpGet code:

    private readonly NSContext _context;
    
        public UsersController(NSContext context)
        {
            _context = context;
        }
    
        [HttpGet]
        public async Task<IActionResult> GetAllUSers([FromQuery] QueryParameters queryParameters)
        {
            IQueryable<User> users = _context.User;
            users = users
                .Skip(queryParameters.Size * (queryParameters.Page - 1))
                .Take(queryParameters.Size);
            return Ok(await users.ToArrayAsync());
        }

    but when I run the program I get this error:

    Does anybody have a solution for this problem?

    Thanks in advance.

    Friday, May 15, 2020 2:25 PM

Answers

  • User-474980206 posted

    If you used the debugger (always a good first step) It’s pretty clear that

    queryParameters.Page

    is zero, so you end up with a negative offset.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 15, 2020 2:39 PM