Introduction
A REST API becomes useful in real projects when it supports more than basic CRUD operations. Clients commonly need to list records from a specific category, search by name or description, sort results by price or date, and split large result sets into manageable pages. These requirements need careful query design, especially when related tables are involved.
In this lesson, we will use a product and category relationship to build EF Core queries and expose them through a REST API endpoint. We will implement filtering, text searching, safe sorting, pagination, and projection. We will also examine why loading unnecessary related entities can hurt performance and how query-string values should be validated.
In the example, a Product entity belongs to a Category entity. The goal is to return a product list with the category name while selecting only the fields required by the client.
1. Querying Related Data
EF Core provides several ways to retrieve related data. Include and ThenInclude are used to load an entity graph. However, a list endpoint usually does not need every entity property. In that situation, projecting directly into a DTO is often a better choice.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public int StockQuantity { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; } = null!;
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public ICollection<Product> Products { get; set; } = new List<Product>();
}The relationship is represented by the Product.CategoryId foreign key and the Product.Category navigation property. If the list only needs the product name, price, and category name, we can define the following DTO.
public sealed class ProductListItemDto
{
public int Id { get; init; }
public string Name { get; init; } = string.Empty;
public decimal Price { get; init; }
public string CategoryName { get; init; } = string.Empty;
}When Select is used for projection, EF Core includes only the selected fields in the SQL query. This reduces the number of columns read from the database and the amount of data transferred to the client. It also keeps the external API contract separate from the persistence entities.
2. Creating a Query-Parameter Model
Managing many query-string parameters individually inside a controller reduces readability. A dedicated model can represent all list options in one place.
public sealed class ProductQueryParameters
{
public string? Search { get; init; }
public int? CategoryId { get; init; }
public decimal? MinPrice { get; init; }
public decimal? MaxPrice { get; init; }
public string Sort { get; init; } = "name_asc";
public int Page { get; init; } = 1;
public int PageSize { get; init; } = 10;
}This model can represent a request such as /api/products?search=keyboard&categoryId=2&sort=price_desc&page=1&pageSize=10. Because query-string values come from the client, defaults, minimum and maximum values, and invalid combinations must be handled explicitly.
3. Filtering and Searching
Building a query step by step is a practical approach for optional filters. We start with AsNoTracking for a read-only query and add conditions only when the corresponding parameter is supplied.
public IQueryable<Product> BuildProductQuery(ProductQueryParameters parameters)
{
IQueryable<Product> query = _dbContext.Products
.AsNoTracking()
.Where(product => product.IsActive);
if (!string.IsNullOrWhiteSpace(parameters.Search))
{
var search = parameters.Search.Trim();
query = query.Where(product =>
product.Name.Contains(search) ||
product.Category.Name.Contains(search));
}
if (parameters.CategoryId.HasValue)
{
query = query.Where(product =>
product.CategoryId == parameters.CategoryId.Value);
}
if (parameters.MinPrice.HasValue)
{
query = query.Where(product =>
product.Price >= parameters.MinPrice.Value);
}
if (parameters.MaxPrice.HasValue)
{
query = query.Where(product =>
product.Price <= parameters.MaxPrice.Value);
}
return query;
}The query is not sent to the database yet. Because it remains an IQueryable, filtering, sorting, projection, and pagination can be composed before execution. This behavior is commonly called deferred execution.
Using a LINQ expression instead of concatenating the search value into SQL text is important. EF Core creates parameters for the query and helps reduce SQL injection risk. User input should never be inserted directly into raw SQL text without a carefully designed and justified approach.
4. Safe Sorting
The client often sends the requested sort field. It is not safe to use that value directly to build dynamic SQL or an unchecked expression. Instead, define an explicit allowlist of supported sort options.
private static IQueryable<Product> ApplySorting(
IQueryable<Product> query,
string? sort)
{
return sort?.ToLowerInvariant() switch
{
"price_asc" => query
.OrderBy(product => product.Price)
.ThenBy(product => product.Id),
"price_desc" => query
.OrderByDescending(product => product.Price)
.ThenBy(product => product.Id),
"name_desc" => query
.OrderByDescending(product => product.Name)
.ThenBy(product => product.Id),
_ => query
.OrderBy(product => product.Name)
.ThenBy(product => product.Id)
};
}Adding ThenBy(product => product.Id) is significant. Products with the same name or price receive a deterministic order. Without a stable order, a record can appear on one page in one request and move to another page in a later request.
5. Pagination
Pagination prevents the API from returning a large result set in a single response. The common offset-based approach calculates how many records to skip and then takes the requested page size.
var page = parameters.Page < 1 ? 1 : parameters.Page;
var pageSize = parameters.PageSize switch
{
< 1 => 10,
> 100 => 100,
_ => parameters.PageSize
};
var skip = (page - 1) * pageSize;
var totalCount = await query.CountAsync(cancellationToken);
var items = await query
.OrderBy(product => product.Name)
.Skip(skip)
.Take(pageSize)
.Select(product => new ProductListItemDto
{
Id = product.Id,
Name = product.Name,
Price = product.Price,
CategoryName = product.Category.Name
})
.ToListAsync(cancellationToken);Skip and Take should be used after a defined and stable OrderBy. Otherwise, the database does not guarantee the order of returned rows. CountAsync obtains the total number of matching records, while the second query retrieves the requested page.
Returning page metadata together with the items makes the API easier for a web client to consume.
public sealed class PagedResult<T>
{
public IReadOnlyList<T> Items { get; init; } = [];
public int Page { get; init; }
public int PageSize { get; init; }
public int TotalCount { get; init; }
public int TotalPages =>
(int)Math.Ceiling(TotalCount / (double)PageSize);
}6. End-to-End Implementation in the Service Layer
Keeping query rules in the service layer instead of placing them in the controller better supports separation of responsibilities in a three-tier architecture. The controller should receive the HTTP request, call the service, and convert the result into an HTTP response.
public async Task<PagedResult<ProductListItemDto>> GetProductsAsync(
ProductQueryParameters parameters,
CancellationToken cancellationToken)
{
var page = parameters.Page < 1 ? 1 : parameters.Page;
var pageSize = Math.Clamp(parameters.PageSize, 1, 100);
IQueryable<Product> query = _dbContext.Products
.AsNoTracking()
.Where(product => product.IsActive);
if (!string.IsNullOrWhiteSpace(parameters.Search))
{
var search = parameters.Search.Trim();
query = query.Where(product =>
product.Name.Contains(search) ||
product.Category.Name.Contains(search));
}
if (parameters.CategoryId.HasValue)
{
query = query.Where(product =>
product.CategoryId == parameters.CategoryId.Value);
}
if (parameters.MinPrice.HasValue)
{
query = query.Where(product =>
product.Price >= parameters.MinPrice.Value);
}
if (parameters.MaxPrice.HasValue)
{
query = query.Where(product =>
product.Price <= parameters.MaxPrice.Value);
}
query = ApplySorting(query, parameters.Sort);
var totalCount = await query.CountAsync(cancellationToken);
var items = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(product => new ProductListItemDto
{
Id = product.Id,
Name = product.Name,
Price = product.Price,
CategoryName = product.Category.Name
})
.ToListAsync(cancellationToken);
return new PagedResult<ProductListItemDto>
{
Items = items,
Page = page,
PageSize = pageSize,
TotalCount = totalCount
};
}Because Category.Name is used inside the projection, an additional Include(product => product.Category) is usually unnecessary for this list query. EF Core can translate the navigation-property access into the required SQL join. Loading the complete entity graph with Include may transfer unnecessary data when the endpoint already projects to a DTO.
A controller action can remain small and focused.
[HttpGet]
public async Task<ActionResult<PagedResult<ProductListItemDto>>> GetProducts(
[FromQuery] ProductQueryParameters parameters,
CancellationToken cancellationToken)
{
if (parameters.MinPrice.HasValue &&
parameters.MaxPrice.HasValue &&
parameters.MinPrice > parameters.MaxPrice)
{
return BadRequest("Minimum price cannot be greater than maximum price.");
}
var result = await _productService
.GetProductsAsync(parameters, cancellationToken);
return Ok(result);
}7. Important Performance and Security Considerations
- Use AsNoTracking: It reduces change-tracking overhead for read-only list queries.
- Project to a DTO: Select only the columns required by the response instead of returning complete entities and relationships.
- Limit page size: Prevent clients from requesting an excessively large page.
- Use a sorting allowlist: Do not construct field names directly from untrusted client input.
- Review indexes: Consider indexes for foreign keys, frequently filtered fields, and common sorting scenarios.
- Be careful with collection relationships: Loading multiple collections in one query can multiply rows and transfer unnecessary data.
- Pass CancellationToken: It helps cancel long-running database work when the client disconnects.
Common Mistakes
Returning entities directly
Returning an entity directly as JSON may serialize navigation properties unexpectedly or expose internal fields. Use DTOs to control the public API contract.
Using Skip and Take without OrderBy
Pagination without ordering can produce inconsistent results. Every paginated query should define an explicit and stable ordering.
Filtering after materialization
Calling ToListAsync first and applying LINQ filters afterward can load every record into application memory. Apply filters before the query is executed.
Allowing unlimited search and page sizes
Unlimited page sizes create performance and availability risks. Validate minimum and maximum values at the API boundary.
Short Practice Exercise
- Add a nullable boolean property named
IsInStocktoProductQueryParameters. - When the value is
true, apply the filterStockQuantity > 0. - Add safe sorting options named
stock_ascandstock_desc. - Include
StockQuantityin the projection DTO. - Test at least three different query-string combinations using Swagger or another HTTP client.
- Verify that total count, total pages, current page, and page size are correct.
Conclusion
List endpoints that work with related data require more than a few LINQ conditions. The query should execute in the database, select only the necessary fields, constrain client input, apply safe and stable sorting, and expose pagination metadata through a clear contract.
The structure created in this lesson allows a web application to filter and paginate products while displaying their category names. In the next stages, these endpoints can be extended with validation, centralized error handling, logging, and client-side data consumption.