Introduction
In real-world applications, loading data with only ToListAsync() is rarely enough. Users usually need to search for text, filter records, sort results by different fields, and navigate through pages. As the number of products, orders, or customers grows, loading every record in a single request creates unnecessary database and memory pressure.
In this lesson, we will extend the repository and application service contracts introduced in the previous lesson. The goal is to use Entity Framework Core and LINQ in the Infrastructure layer without exposing database details to the Presentation layer. To achieve this, we will design reusable pagination request and response models.
EF Core translates most LINQ expressions into SQL understood by the selected database provider. A query is generally not executed until its results are consumed. Therefore, filtering, sorting, projection, and pagination should be performed in the database whenever possible.
Designing a listing contract
The Application layer should define which parameters a listing use case accepts. This model should not depend directly on EF Core or SQL Server. We can create a reusable pagination request as follows:
namespace Application.Common.Models;
public sealed class PaginationRequest
{
public int PageNumber { get; init; } = 1;
public int PageSize { get; init; } = 10;
public string? Search { get; init; }
public string? SortBy { get; init; }
public bool SortDescending { get; init; }
}
PageNumber should start at one. A maximum value should also be enforced for PageSize. Otherwise, a client could send pageSize=1000000 and place unnecessary load on the database and application.
For a simple implementation, we can expose effective values that protect the query:
public sealed class PaginationRequest
{
private const int DefaultPageSize = 10;
private const int MaxPageSize = 100;
public int PageNumber { get; init; } = 1;
public int PageSize { get; init; } = DefaultPageSize;
public string? Search { get; init; }
public string? SortBy { get; init; }
public bool SortDescending { get; init; }
public int EffectivePageNumber => PageNumber < 1 ? 1 : PageNumber;
public int EffectivePageSize =>
PageSize < 1 ? DefaultPageSize : Math.Min(PageSize, MaxPageSize);
}
This approach works for straightforward scenarios. In larger applications, FluentValidation can reject invalid values and return a clear validation response to the client. For example, the application may treat a negative page number as an invalid request instead of silently correcting it. This decision is part of the API contract and should be applied consistently across the project.
Creating a pagination response
The client needs more than the current collection of records. It also needs the total number of records and pages so that it can render navigation controls.
namespace Application.Common.Models;
public sealed class PaginationResponse<T>
{
public IReadOnlyCollection<T> Items { get; init; } = [];
public int PageNumber { get; init; }
public int PageSize { get; init; }
public int TotalCount { get; init; }
public int TotalPages =>
PageSize == 0 ? 0 : (int)Math.Ceiling(TotalCount / (double)PageSize);
public bool HasPreviousPage => PageNumber > 1;
public bool HasNextPage => PageNumber < TotalPages;
}
We return a DTO instead of an entity. This prevents Domain or Infrastructure objects from leaking into the API boundary. For a product listing, we can define a compact projection model:
public sealed record ProductListItemDto(
int Id,
string Name,
decimal Price,
bool IsActive);
This DTO contains only the fields required by the listing screen. Large descriptions, related collections, or internal fields should not be selected when they are not needed.
Building the LINQ query step by step
Let us define a repository method that returns a paged product list:
public interface IProductRepository
{
Task<PaginationResponse<ProductListItemDto>> GetPagedAsync(
PaginationRequest request,
CancellationToken cancellationToken = default);
}
This contract describes the Application requirement. Depending on the chosen dependency direction, Infrastructure may reference Application so that it can use the DTO, or the repository may return an entity or projection model that is mapped by an application service. The decision should consider dependency rules, query efficiency, and ownership of mapping responsibilities.
The Infrastructure implementation can build the query incrementally:
public async Task<PaginationResponse<ProductListItemDto>> GetPagedAsync(
PaginationRequest request,
CancellationToken cancellationToken = default)
{
var query = _context.Products
.AsNoTracking()
.Where(product => product.IsActive)
.AsQueryable();
if (!string.IsNullOrWhiteSpace(request.Search))
{
var search = request.Search.Trim();
query = query.Where(product =>
product.Name.Contains(search));
}
query = request.SortBy?.ToLowerInvariant() switch
{
"price" => request.SortDescending
? query.OrderByDescending(product => product.Price)
: query.OrderBy(product => product.Price),
"name" => request.SortDescending
? query.OrderByDescending(product => product.Name)
: query.OrderBy(product => product.Name),
_ => query.OrderBy(product => product.Id)
};
var totalCount = await query.CountAsync(cancellationToken);
var items = await query
.Skip((request.EffectivePageNumber - 1) * request.EffectivePageSize)
.Take(request.EffectivePageSize)
.Select(product => new ProductListItemDto(
product.Id,
product.Name,
product.Price,
product.IsActive))
.ToListAsync(cancellationToken);
return new PaginationResponse<ProductListItemDto>
{
Items = items,
PageNumber = request.EffectivePageNumber,
PageSize = request.EffectivePageSize,
TotalCount = totalCount
};
}
The query is assembled in stages. First, active products are selected. If a search value exists, a Where clause is added. The query is then ordered by an allowed field. CountAsync calculates the total number of matching records. Finally, Skip and Take retrieve only the requested page.
Managing sort fields safely
A client-provided SortBy value should not be converted directly into a dynamic SQL expression. Building expressions or raw SQL from uncontrolled text creates security and maintenance risks. Instead, explicitly map supported names to known properties.
query = request.SortBy?.ToLowerInvariant() switch
{
"createdat" => request.SortDescending
? query.OrderByDescending(x => x.CreatedAt)
: query.OrderBy(x => x.CreatedAt),
"price" => request.SortDescending
? query.OrderByDescending(x => x.Price)
: query.OrderBy(x => x.Price),
_ => query.OrderBy(x => x.Id)
};
A stable default ordering is important. If several records have the same value, add a secondary ordering criterion to reduce records moving between pages:
query = query
.OrderByDescending(x => x.CreatedAt)
.ThenBy(x => x.Id);
Using query strings in the controller
ASP.NET Core model binding can bind query string values to a complex request model. This keeps the controller focused:
[HttpGet]
public async Task<ActionResult<PaginationResponse<ProductListItemDto>>> GetProducts(
[FromQuery] PaginationRequest request,
CancellationToken cancellationToken)
{
var result = await _productService.GetPagedAsync(request, cancellationToken);
return Ok(result);
}
An example request is:
GET /api/products?pageNumber=2&pageSize=20&search=keyboard&sortBy=price&sortDescending=trueThe controller should not know about the repository or DbContext. HTTP parameters are bound to an Application contract, the use case is invoked, and the result is converted to an HTTP response.
Offset pagination and its limitations
Using Skip and Take is commonly called offset pagination. It is usually sufficient for administration panels and standard listing screens. However, on later pages of very large tables, a high Skip value may require the database to process many rows before returning the requested page.
For these cases, keyset or seek pagination can be considered. For example, the application can request records after the last visible Id by using Where(x => x.Id > lastId). This replaces a page number with a continuation value and can be more efficient for infinite scrolling. However, offset pagination is easier to understand when users must navigate directly to a specific page.
Common mistakes
- Loading every record into memory: Calling
ToListAsyncbefore filtering and pagination transfers unnecessary data. - Executing LINQ too early: Calling
AsEnumerableorToListbefore the query is complete can move work from the database to application memory. - Tracking read-only results:
AsNoTrackingis usually appropriate for read-only listing operations. - Paginating without ordering: Without a deterministic
OrderBy, pages may return inconsistent results. - Trusting SortBy blindly: Accept only explicitly supported sort fields.
- Counting the wrong query: Call
CountAsyncbefore applyingSkipandTake. - Returning entities as API responses: Directly exposing entities may reveal unnecessary fields and create navigation-property cycles.
Practice exercise
Create an Order listing use case in the project. Implement the following requirements:
- Create an
OrderPaginationRequestwith page number, page size, customer-name search, and date-range fields. - Return an
OrderListItemDtocontaining the order number, total amount, status, and creation date. - Write a LINQ query that excludes cancelled orders.
- Use descending creation date as the default ordering.
- Apply
CountAsync,Skip,Take, andSelectin the correct sequence. - Test a second page, a different page size, and a search term through Swagger.
Inspect the SQL logs to verify that filtering and pagination are sent to SQL Server. When working with large tables, also evaluate the query plan and the indexes used by the database.
Conclusion
In this lesson, we modeled listing requirements through Application contracts instead of solving them directly inside controllers. Reusable request and response models allow the same pagination behavior to be applied to different entities. We built LINQ queries using controlled filtering, sorting, projection, and pagination steps.
The central principle is to construct the IQueryable so that as much work as possible is performed by the database. Safe sort-field mapping, DTO projection, AsNoTracking, stable ordering, and maximum page-size limits directly affect application performance and maintainability. In the next stage, we will strengthen these contracts with validation, application services, and consistent API response standards.