skip to Main Content

I’m doing pagination with EF core 6 and dotnet core.

public async Task<IEnumerable<CommentResponse>> GetCommentOfPostAsync(Guid PostId, int PageNumber, int PageSize)
    => await _context.Comments
                    .Include(comment => comment.User)
                    .OrderBy(comment => comment.CommentId)
                    .Select(
                        data => new CommentResponse
                        {
                            CommentId = data.CommentId,
                            UserId = data.UserId,
                            Avatar = data.User.Avatar,
                            CommentText = data.CommentText,
                            Username = data.User.Username,
                            Created = data.Created
                        }
                    )
                    .Skip(PageNumber - 1 * PageSize)
                    .Take(PageSize)
                    .ToListAsync();

But when I pass PageSize > 1 it always returns an error.

Npgsql.PostgresException (0x80004005): 2201X: OFFSET must not be negative

Why am I getting this error and how to solve it.
Thanks very much.

2

Answers


  1. Skip((PageNumber – 1) * PageSize)

    Login or Signup to reply.
  2. You are falling foul of the operator precedence rules – the expression .Skip(PageNumber - 1 * PageSize) is being evaluated as .Skip(PageNumber - (1 * PageSize)) (note the brackets) due to multiplication having higher precedence than subtraction.

    As a result, the value being passed to Skip isn’t what you want it to be and based on that error message, is a negative value.

    A general rule of thumb I was taught about this to remember the acronym "BODMAS" to know the precedence rules:

    • Brackets
    • Order (x^5 for example)
    • Division
    • Multiplication
    • Addition
    • Subtraction
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search