Skip to content

Custom list endpoints with QueryKit ​

Use QueryKit for a domain-specific list whose filter and projection do not fit the generic CRUD controller. It composes filters and a sort map on IQueryable, counts the filtered result, applies Skip/Take, then materializes the requested page. With an EF Core source, keep these operations on the provider-backed query so the database performs filtering and paging.

The examples use app-owned InvoiceReadModel, InvoiceListItem, and AppDbContext types. Define those types in the host or adapt the example to the read model and item types in your application. The framework imports used by the fragments are:

csharp
using GrydCrud.API.Controllers;
using GrydCrud.Cqrs.Extensions;
using GrydCrud.Cqrs.Handlers;
using GrydCrud.Cqrs.Queries;
using GrydCrud.Core.Configuration;
using GrydCrud.Core.QueryKit.Filters;
using GrydCrud.Core.QueryKit.Requests;
using GrydCrud.Core.QueryKit.Sorting;
using GrydCrud.Core.QueryKit.Spec;
using GrydCrud.Extensions;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

Add the host namespaces that contain the app-owned types.

Request and query ​

AggregateQueryRequest provides Page, PageSize, SortBy, SortDirection, Search, and IncludeDeleted. The controller normalizes page values using CrudOptions and sends a CustomListQuery<TRequest, TItem> it builds itself. SortDirection accepts QueryKit's asc/desc and the CRUD contract's Ascending/Descending (what the Gryd.UI data source sends), case-insensitive; any other value sorts ascending.

csharp
public sealed record ListInvoicesRequest : AggregateQueryRequest
{
    public Guid? ClientId { get; init; }
}

There is no query class to declare. CustomListQuery is sealed: MediatR resolves the handler by the request's runtime type, so a subclass would reach no handler registered by AddCustomListHandler. The sortable fields are not declared on the query either; they are the sort map's (next section).

InvoiceListItem and ClientId are application-owned types and fields. The request and query contracts are maintained in AggregateQueryRequest and CustomListQuery.

Filters and sorting ​

Filters take (IQueryable<TReadModel>, TRequest) and return the narrowed query. Sort mappings use expression trees so the provider can translate the selected key into SQL:

csharp
public sealed class InvoicesByClientFilter
    : IQueryFilter<ListInvoicesRequest, InvoiceReadModel>
{
    public IQueryable<InvoiceReadModel> Apply(
        IQueryable<InvoiceReadModel> query,
        ListInvoicesRequest request) => request.ClientId is Guid clientId
        ? query.Where(row => row.ClientId == clientId)
        : query;
}

public sealed class InvoiceSortMap : QuerySortMap<ListInvoicesRequest, InvoiceReadModel>
{
    public InvoiceSortMap()
    {
        Map("referenceMonth", row => row.ReferenceMonth);
        Map("clientName", row => row.ClientName);
        Map("status", row => row.Status);
        SetDefault("referenceMonth", "desc");
        SetTieBreaker(row => row.Id);
    }
}

The sort map is the only list of sortable fields. The handler validates sortBy against it (through the spec builder, which exposes AllowedSortFields and IsSortFieldAllowed), so the field a request may ask for and the field the query can order by are the same list. A list with no sort map refuses any sortBy.

SetTieBreaker names a unique key that orders rows sharing the sort value, ascending, after the requested field. Without it, a sort on a non-unique field (status, isActive) lets rows move between LIMIT/OFFSET pages. When no mapped field applies (no sortBy and no default), the tie-breaker is the only ordering, so a page never runs over an unordered query. Set it on every sort map.

For this example, the application read model and API item are:

csharp
public sealed record InvoiceReadModel(
    Guid Id, DateOnly ReferenceMonth, string ClientName, string Status, Guid ClientId);

public sealed record InvoiceListItem(
    Guid Id, DateOnly ReferenceMonth, string ClientName, string Status);

DefaultQuerySpecBuilder<TRequest, TReadModel> composes registered filters and an optional IQuerySortApplier<TRequest, TReadModel>. The filter interface, sort map and builder signatures are available in the QueryKit source.

Handler ​

The base class requires a provider-backed root query and an item mapper. Its default CountAsync and ToListAsync hooks call LINQ synchronously; override them when the provider has asynchronous query methods such as EF Core's CountAsync and ToListAsync.

csharp
public sealed class ListInvoicesHandler
    : CustomListQueryHandlerBase<ListInvoicesRequest, InvoiceReadModel, InvoiceListItem>
{
    private readonly AppDbContext _db;

    public ListInvoicesHandler(
        AppDbContext db,
        IQuerySpecBuilder<ListInvoicesRequest, InvoiceReadModel> specBuilder,
        IQueryRequestNormalizer normalizer,
        CrudOptions options)
        : base(specBuilder, normalizer, options) => _db = db;

    protected override IQueryable<InvoiceReadModel> BuildBaseQuery(
        ListInvoicesRequest request, CancellationToken cancellationToken) =>
        _db.Invoices.AsNoTracking().Select(invoice => new InvoiceReadModel(
            invoice.Id, invoice.ReferenceMonth, invoice.Client.Name, invoice.Status, invoice.ClientId));

    protected override InvoiceListItem MapToItem(
        InvoiceReadModel row, ListInvoicesRequest request) =>
        new(row.Id, row.ReferenceMonth, row.ClientName, row.Status);
}

The query base applies the composed filter and sort before count and page. It then applies Skip((Page - 1) * PageSize) and Take(PageSize) before materialization. Keep any additional predicates in the returned IQueryable; materializing first would move work out of the database. See the maintained CustomListQueryHandlerBase for the extension points.

Controller and registration ​

CustomListController<TRequest, TItem> requires IMediator and CrudOptions. It is an HTTP adapter only (normalize paging, send the query, map the result), so the derived controller declares its route and nothing else:

csharp
[Route("api/v{version:apiVersion}/invoices/custom-list")]
public sealed class InvoicesController : CustomListController<ListInvoicesRequest, InvoiceListItem>
{
    public InvoicesController(IMediator mediator, CrudOptions options) : base(mediator, options) { }
}

Register QueryKit through AddGrydCrud (it includes the default spec builder and request normalizer), then add the application-specific filter, sorter and handler:

csharp
builder.Services.AddGrydCrud();
builder.Services.AddScoped<
    IQueryFilter<ListInvoicesRequest, InvoiceReadModel>, InvoicesByClientFilter>();
builder.Services.AddScoped<
    IQuerySortApplier<ListInvoicesRequest, InvoiceReadModel>, InvoiceSortMap>();
builder.Services.AddCustomListHandler<
    ListInvoicesRequest, InvoiceListItem, ListInvoicesHandler>();

Response ​

The endpoint answers 200 with the platform's list envelope, PagedResult<TItem>, the same body as the CRUD list and every module list. scope is always null: a custom list is not scope-capable. The sort is not echoed; the client already holds what it requested.

json
{
  "items": [
    { "id": "6a1c…", "referenceMonth": "2026-09-01", "clientName": "Acme", "status": "open" }
  ],
  "totalCount": 41,
  "pageNumber": 2,
  "pageSize": 20,
  "totalPages": 3,
  "hasNext": true,
  "hasPrevious": true,
  "scope": null
}

A handler result maps to the envelope with CustomListQueryResult<TItem>.ToPagedResult(), for a consumer that answers from its own controller.

A sortBy the sort map does not declare answers 400 application/problem+json with code: "VALIDATION_ERROR" and the field error on errors.sortBy, the shape of every per-field validation error. The text comes from the error catalog in the request culture:

json
{
  "status": 400,
  "detail": "The requested sort field is not supported.",
  "code": "VALIDATION_ERROR",
  "errors": { "sortBy": ["The requested sort field is not supported."] }
}

The controller and registration helper signatures are maintained in CustomListController and AddCustomListHandler.

Keep sort fields whitelisted and apply tenant restrictions to the base query through the host's tenant-aware DbContext; QueryKit does not establish tenant identity or add authorization by itself.

Released under the MIT License.