ASP.NET Core Web API Interview Question #116

How should an API implement pagination with EF Core?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

Apply deterministic ordering, then use Skip and Take for straightforward offset pagination. Validate page and page-size values and enforce a maximum page size.

Detailed Explanation

Apply deterministic ordering, then use Skip and Take for straightforward offset pagination. Validate page and page-size values and enforce a maximum page size.

Offset pagination is simple but can become expensive or inconsistent for very large, frequently changing datasets. Keyset or cursor pagination may be a better design for high-scale sequential navigation.

Code Example

var page = await _db.Products
    .AsNoTracking()
    .OrderBy(x => x.Id)
    .Skip((pageNumber - 1) * pageSize)
    .Take(pageSize)
    .Select(x => new ProductResponse
    {
        Id = x.Id,
        Name = x.Name
    })
    .ToListAsync(token);