↑↓ to navigate Enter to open "…" all these words ANDOR to combine

Auth & the edge · No. 28

Generic entity controllers and the dynamic query contract (ADR-034)

The write-once REST surface every entity inherits. How list, page, lookup, by-id, create, and delete come from two base classes, plus a bounded OData-lite query contract that is dynamic over the wire but never open SQL in the engine.


Here is a controller that looks fine until you have a second entity:

[ApiController]
[Route("products")]
public sealed class ProductsController : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetAll(
        string? sort, string? dir, int page = 1, int size = 20,
        string? name = null, decimal? minPrice = null)   // ad-hoc filter params
    {
        var q = _db.Products.AsQueryable();
        if (name is not null) q = q.Where(p => p.Name.Contains(name));      // hand-rolled
        if (minPrice is not null) q = q.Where(p => p.Price >= minPrice);    // hand-rolled
        if (sort == "name")
            q = dir == "desc" ? q.OrderByDescending(p => p.Name) : q.OrderBy(p => p.Name);
        var items = await q.Skip((page - 1) * size).Take(size).ToListAsync();
        return Ok(items);   // no total count, no page-size cap, leaks the entity to the wire
    }
    // ... GetById, Create, Delete, each subtly different from CategoriesController
}

Now write CategoriesController, OrdersController, and twenty more. A different person writes each one in a different sprint. One paginates with page/size, the next with pageNumber/pageSize. One filters with ?name=, another with ?nameContains=. One returns a total count, most do not. One forgets the Take clamp entirely, so a query with no filter streams the whole table into memory. Each leaks its EF entity straight to JSON, so a column rename is a silent wire break. This is the single largest pile of boilerplate a modular monolith accumulates as it grows, and the pile drifts in shape with every commit.

A client cannot learn one query dialect and reuse it. It learns one per resource, defensively, and still gets surprised. And the day you want a uniform feature (a max page size, a filter operator, a sparse-fieldset projection) you are editing dozens of controllers by hand and missing some.

Why it matters

Most entities need the same six things: list them, page through them, fetch a lightweight id/name list for a dropdown, get one by id, create one, delete one. That surface is so uniform that hand writing it per entity is pure repetition, and repetition without a single source of truth is how drift gets in. The shape that should be identical across a hundred entities ends up almost-identical, which is worse than identical because callers cannot rely on it.

There is also a safety dimension. A read endpoint with no upper bound on result size is one missing Where clause away from a full-table load that pins a database. A filter parameter assembled from raw client input is an injection and over-fetch surface. If those guards are the responsibility of each author, they are missing somewhere.

ADR-034 records the framework's opposite default: write the resource surface and the query contract once, on a base class, and let every entity inherit it. A concrete controller becomes a few lines that close the generic type parameters. The verbs, routes, filtering, sorting, pagination, field projection, include behavior, and the safety ceiling all come from the base. New entities cost almost nothing and cannot drift in shape.

The MMCA answer: two base classes and an OData-lite contract

The read surface is EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>. It is an [ApiController] with [Route("[controller]")] and [ApiVersion("1.0")], and it exposes five GET routes that any entity inherits for free: [HttpGet] for the capped list, [HttpGet("paged")] for the filterable/sortable page, [HttpGet("export")] for a streamed CSV of the same filtered, sorted, projected rows, [HttpGet("lookup")] for an id/name dropdown collection (CollectionResult<BaseLookup<TIdentifierType>>), and [HttpGet("{id}")] for a single record. The same base declares two more GET routes that are opt-in rather than inherited: [HttpGet("cursor")], a keyset page (ADR-145, covered below), and [HttpGet("changes")], a change feed of upserts and soft-delete tombstones (ADR-144). Each exists only on a controller that carries its marker attribute; on every other controller the action is removed from the routing table and the API document.

The write surface is AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest>. It inherits the read surface and adds [HttpPost] create (returning 201 Created) and [HttpDelete("{id}")] (returning 204 NoContent). The create action is decorated [Idempotent], so a retried POST carrying the same Idempotency-Key header replays the original response instead of creating a duplicate (ADR-017). The base resolves the 201's Location header before it returns: through the route named by GetByIdRouteName (Get{EntityName}ById by default) when a concrete controller declares one, and otherwise by appending the new id to the collection path the POST targeted, which is where the inherited [HttpGet("{id}")] answers. Naming the by-id route is therefore optional.

A third base, CrudEntityControllerBase, derives from the write surface and adds [HttpPut("{id}")] update, conditional on If-Match and also [Idempotent] (ADR-099). This article stays on the two bases it extends.

A concrete controller needs only the constructor. The one below also names its by-id route, which is optional, so its Location resolves through the named route:

[Route("products")]
public sealed class ProductsController(
    IEntityQueryService<Product, ProductDTO, int> queryService,
    ICommandHandler<CreateProductRequest, Result<ProductDTO>> createHandler,
    ICommandHandler<DeleteEntityCommand<Product, int>, Result> deleteHandler,
    ILogger<EntityControllerBase<Product, ProductDTO, int>> logger)
    : AggregateRootEntityControllerBase<Product, ProductDTO, int, CreateProductRequest>(
        queryService, createHandler, deleteHandler, logger)
{
    // Optional: with this name present, POST links its Location through the GetProductById route.
    [HttpGet("{id}", Name = "GetProductById")]
    public override Task<ActionResult<ProductDTO>> GetByIdAsync(
        int id, bool includeFKs = true, bool includeChildren = false,
        [FromQuery] string? fields = null, CancellationToken cancellationToken = default)
        => base.GetByIdAsync(id, includeFKs, includeChildren, fields, cancellationToken);
}

// GET, GET /paged, GET /export, GET /lookup, POST, and DELETE /{id} are inherited
// unchanged, and GET /{id} keeps the base behavior under its new name, with filter,
// sort, page, and field projection on the read routes and idempotent create on the write route.

What that inheritance buys is a uniform query contract on every list and detail route:

  • Sparse fieldsets. A comma-separated fields query parameter drives a server-side projection. QueryFieldService.ApplyFieldSelection builds a MemberInit expression that selects only the requested writable properties, so only those columns leave the database, and the compiled expression is cached per entity type and field set so a repeated fields= request does not rebuild the tree. That cache is capped at 512 entries, since the field set is client-supplied; past the cap a request skips server-side projection instead of growing the cache further, though the response body is still trimmed to the requested fields. Every requested name must resolve to a field the DTO declares, so an entity-only name is refused. When the read materializes entities and then maps them, each name must also be a writable entity property, so read-only and computed properties are rejected at validation on that path, since its projection needs setters; on the projection-pushdown path described below only the DTO check applies.
  • Dynamic per-type filtering. The paged route binds Dictionary<string, (string Operator, string Value)> filters through [ModelBinder(typeof(QueryFilterModelBinder))]. The binder parses ?filters[Name].operator=contains&filters[Name].value=shirt style keys (case-insensitive, incomplete pairs silently dropped, at most 50 filters honored with the surplus dropped) into the dictionary. QueryFilterService.ApplyFilters then resolves one IFilterStrategy per property CLR type from a strategy registry (string, bool, int, long, DateTime, decimal, Guid and their nullables, plus the Email value object, out of the box, and for a strongly typed identifier column (ADR-115) a strategy built on first use and memoized beside the built-ins, so adopting identifier wrappers needs no registration call), and each built-in strategy declares its operator set through SupportedOperators. This is the load-bearing constraint: filtering is dynamic over the wire but it is not free-form expression evaluation. Every property routes through a registered strategy, and QueryFilterService.ValidateFilters rejects, before the database is touched, a key the DTO does not declare (or a dotted path the server did not map), a resolved path deeper than three navigation segments, an unknown property, an unsupported operator, and a value the strategy cannot parse. Operator and value checks are opt-in for a custom strategy: SupportedOperators defaults to null, which skips operator validation, and CanParseValue defaults to true. The built-in Email strategy declares its operators but takes that CanParseValue default, so an email filter value is not checked at validation.
  • Sort. sortColumn and sortDirection feed QueryFieldService.ApplySorting, an OrderBy("<col> ascending|descending") over the entity property the DTO name maps to. On a paginated query the pipeline appends Id ascending as a final tie-break key, so Skip/Take runs over a total order even when the requested sort column has duplicates.
  • Pagination and the X-Pagination header. The paged route clamps the requested page size with Math.Min(pageSize, MaxPageSize). MaxPageSize reads ApplicationSettings.MaxPageSize through IOptions<ApplicationSettings>, falls back to 500, and is itself clamped to the range 1 to EntityQueryPipeline.MaxUnboundedResultLimit (1000), so a configured value above 1000 has no effect and the pagination metadata never promises a page size the pipeline does not serve. The pagination metadata (total count, page size, current page) is serialized into the X-Pagination response header as JSON, and the same metadata also travels in the body: the action returns the whole PagedCollectionResult, which carries paginationMetadata beside the items, so a client can read either.
  • A streamed CSV export. [HttpGet("export")] reuses the same filter, sort, and fields contract and writes rows to the response body a page at a time, so the file never lands in memory. Row scoping is fail-closed: the export reads through the same GetReadSpecificationAsync hook as the list routes, and when that hook resolves to no specification the request is refused with a 403 (Export.RowScopeRequired) before anything is queried, unless the controller opts in through AllowUnscopedExport. It stops at MaxExportRows (ApplicationSettings.MaxExportRows, where an unset, zero, or negative value falls back to 100,000), announces that ceiling up front in an X-Export-Row-Limit header, and ends a truncated file with a trailing marker row: headers are frozen the moment the first body byte is flushed, so the marker is the only signal still writable once the export is under way. It takes no includeChildren parameter, since a child collection has no faithful representation in a flat CSV cell, and its column set drops every DTO property that cannot render as a scalar cell (a binary row version, a collection), refusing a fields= request that names one. A controller whose DTO computes a scalar from a loaded navigation (a count of children, a parent's name) loads it through the ExportIncludeChildren and ExportIncludeFKs overrides, both false by default.
  • A last-resort ceiling. Independent of the API clamp, EntityQueryPipeline.MaxUnboundedResultLimit = 1000 caps any unpaginated query with query.Take(MaxUnboundedResultLimit). Even a direct service caller who omits pagination entirely cannot trigger an unbounded full-table load.
  • Two include paths. includeFKs and includeChildren select navigation loading, and EntityQueryPipeline runs one of two strategies. PATH 1 handles source-supported includes via EF Core .Include() translated to SQL (forcing split-query when a child collection is included, so pagination does not truncate the JOIN-expanded rows). PATH 2 handles includes the source cannot JOIN by materializing the page first, then batch-loading related data via an INavigationPopulator (the cross-source loader of ADR-002).

Under all of this sits EntityQueryService, which validates the parameters up front, runs the pipeline, and by default projects the materialized entities to DTOs through an injected IEntityDTOMapper (the manual mapping of ADR-001). A module that registers an IEntityDTOProjector gets projection pushdown on list reads instead: a second constructor takes the projector, and when the read is untracked and every requested include is source-supported, the provider selects the DTO's columns directly and the mapper is never involved. On that path the server-side fields projection is not applied, so the selected columns are the DTO's and fields trims the response after the read. Every action returns a Result, and a failure flows through HandleFailure(result.Errors) into the same RFC 9457 Problem Details shape the rest of the API uses (ADR-013). The wire speaks DTO names; the engine speaks entity names; a per-service DTOToEntityPropertyMap translates between them for filtering and sorting.

Cursor paging, opt-in beside the offset page

The offset page has two weaknesses a scrolling client feels. Page 37 costs the database a scan of the 36 pages before it, and a row inserted ahead of the reader's position shifts every later row by one, so "load more" over offsets can show a row twice or skip one. ADR-145 answers both with a keyset read that sits beside paged rather than replacing it, because a server-paged grid still needs page numbers and a total.

The read is GetCursorPageAsync, answering GET {controller}/cursor?sortColumn=&sortDirection=&cursor=&pageSize=, and it exists only on a controller that carries [SupportsCursorPaging]. The action is declared on the base with an internal [OptInAction(typeof(SupportsCursorPagingAttribute))] convention that removes it from the application model unless the controller opts in, so a controller without the marker has no route and an unchanged API document. The marker is inherited, so putting it on an abstract base opts in a whole family of controllers.

  • One validated sort column plus an Id tie-break. sortColumn is checked against the same response contract and DTOToEntityPropertyMap as the list read, and the order is (sortKey, Id) with the tie-break always ascending; no sort column pages by Id alone. sortDirection must be empty, asc or desc, and anything else is a 400 before the read runs.
  • An opaque cursor. The cursor is a versioned base64url token holding the last row's sort value and Id. A malformed one is a 400, never a silent first page. It is opaque by contract, not by cryptography: it carries only values the caller already received.
  • No total. The read takes one row more than the page, and that probe row is what decides whether NextCursor is null. There is no count query, no X-Pagination header, no fields projection, no includes and no filter dictionary: the keyset read takes the controller's GetReadSpecificationAsync scope and nothing else.
  • The same ceiling. The page size is clamped by the same Math.Min(pageSize, MaxPageSize) as the paged route.

MMCA.Helpdesk is the only adopter: its TicketsController carries the marker, and its ticket list requests Tickets/cursor?sortColumn=id&sortDirection=desc, then passes back each NextCursor until the server returns none. Neither MMCA.ADC nor MMCA.Store opts in, so their API documents carry no cursor route.

The trade is explicit. A cursor client cannot jump to page N or show a total. A cursor does not record its sort, so a client keeps sortColumn and sortDirection fixed for the life of one. The seek is only as cheap as the index behind the sort column: sorting by Id rides the primary key, and nothing creates an index for any other column. A custom query service that does not derive from EntityQueryService must also implement GetPageByCursorAsync, or the endpoint answers 500.

The line where the user's value stops being code

There is one more constraint under all of this, and it is the one that decides whether a user-supplied filter DSL is a good idea or a liability. When a strategy builds its predicate, the property name is interpolated into the expression string but the user's value never is:

"CONTAINS" => query.Where(DynamicQueryConfig.Parameterized, $"{property}.Contains(@0)", value),
"EQUALS" => query.Where(DynamicQueryConfig.Parameterized, $"{property} == @0", value),

The asymmetry is deliberate. property has already survived ValidateFilters, so it is a name from a known allow-list rather than user text. value is arbitrary user input, and it is passed as the @0 argument, never concatenated into the predicate.

That alone is the injection story, but the DynamicQueryConfig.Parameterized part is the half most teams miss. System.Linq.Dynamic.Core defaults UseParameterizedNamesInDynamicQuery to false, which turns each @0 argument into a ConstantExpression. EF inlines constants. So with the default config, filters["Name"] = ("EQUALS", "Widget") emits:

WHERE [Name] = 'Widget'

A distinct SQL string per distinct filter value. Every search term a user types costs its own SQL Server plan-cache entry and misses EF's compiled-query cache on the way in. The filter DSL you built for convenience quietly becomes a plan-cache eviction engine, and the symptom is not a slow query, it is the whole instance getting slower as the cache churns.

Flipping the flag on makes the value reachable through a member access instead, so EF parameterizes it and one plan serves every value. The config is a single shared static, because building a ParsingConfig per call would reintroduce the parse cost it exists to avoid. QueryParameterizationTests guards it by sampling the emitted SQL: string EQUALS, string CONTAINS, an int comparison, two values of one filter producing identical SQL, and sorting. It does not walk the strategy registry, so a new or custom strategy that forgets the config is outside what it checks.

This is worth internalizing as a general shape: the same change bought both a closed injection surface and a fixed plan-cache hit rate, because both problems have the same root cause, which is a user's value ending up in the text of a query instead of beside it.

The same rule for hand-written SQL

The filter DSL is not the only path from a caller's value to the database. Some reads need a window function, a recursive CTE, or a vendor-specific operator that LINQ cannot express, and ADR-125 gives those exactly one door: IRawSqlQueryExecutor. Its two methods, QueryAsync<T> and QuerySingleOrDefaultAsync<T>, accept a FormattableString and nothing else. The provider turns every interpolation hole into a command parameter, and a concatenated statement is a plain string that does not compile against either method:

// Compiles: customerId becomes a command parameter, and the statement text stays stable.
var count = await rawSql.QuerySingleOrDefaultAsync<int>(
    $"SELECT COUNT(*) FROM Orders WHERE CustomerId = {customerId}", cancellationToken);

// Does not compile: concatenation produces a string, not a FormattableString.
// await rawSql.QueryAsync<OrderRow>("SELECT * FROM Orders WHERE Name = '" + name + "'");

The signature closes the door it owns, but it cannot stop module code from calling EF Core directly, where FromSqlRaw, SqlQueryRaw, ExecuteSqlRaw, and ExecuteSqlRawAsync take a plain string and sit one word away from their parameterizing twins. So the ban is a fitness test rather than a guideline: RawSqlConventionTestsBase.ModuleCode_UsesParameterizedSqlOnly scans the source of every mapped module, fails on any of those four members, and names FromSql/SqlQuery/ExecuteSql or IRawSqlQueryExecutor as the replacement in its failure message, so the test output is the instruction. A scan that finds no module directories fails instead of passing vacuously. MMCA.Store subclasses the base with its own architecture map and an explicitly empty AllowedFiles list, so every new raw call site in the store fails its architecture test suite. The root cause is the one above: the value belongs beside the query text, never inside it, and plan reuse comes with it.

The limits are worth stating. FormattableStringFactory.Create can still wrap an already-concatenated string, so the contract blocks the careless path rather than proving safety. The test is a textual scan of exactly four member names, so SQL reaching the database through raw ADO.NET or a micro-ORM is outside it. And the executor is relational only: a host whose default source is Cosmos DB has no registration, so a service that injects the interface there fails to resolve: at container build in Development, where the default host validates the container, and on first resolution elsewhere.

Trade-offs, honestly

A generic, dynamically queryable contract coupled to the entity model is a real trade against narrow bespoke endpoints. ADR-034 names the costs rather than hiding them.

  • The wire contract tracks the response contract. A client sort or filter key must name a field the DTO declares (the default FieldContract is QueryFieldContract.For<TEntityDTO>()), so a DTO change is an API change by default, and an entity column the DTO does not expose is not addressable from the wire. The server-authored DTOToEntityPropertyMap is the escape hatch that decouples the two: a subclass overrides the map to point a DTO field name (CategoryName) at an entity path (Category.Name), and the wire name stops moving with the column. Overriding FieldContract with null resolves client names against the entity instead, which is a deliberate opt-out, not a default.
  • Dynamic filtering is an injection and over-fetch surface, and it is bounded, not open. Arbitrary client-supplied property/operator/value triples are an attack surface. The framework bounds it in layers: the binder honors at most 50 filters; ValidateFilters refuses a key outside the DTO contract, a dotted path the server did not author, a path deeper than three navigation segments, an unsupported operator, and an unparseable value, all as a 400 before any query runs; each type is filtered only by its registered IFilterStrategy rather than free-form expression evaluation; and MaxUnboundedResultLimit caps rows. The operator and value checks depend on the strategy declaring them: the built-ins declare their operators, the built-in Email strategy leaves the value check at its permissive default, and a custom strategy must opt into both. This is per-type strategy filtering, deliberately narrower than full OData.
  • The create Location takes one of two shapes. CreateAsync resolves the header before it returns Created: an absolute link through the route named by GetByIdRouteName when that route resolves, otherwise a host-relative path built from the collection the POST targeted plus the new id. A controller that only closes the type parameters still answers a working 201, but which shape its clients see depends on whether the derived controller declared the named route, and a controller that names its by-id route differently has to override GetByIdRouteName to keep the absolute form.
  • Generic endpoints are less self-documenting than bespoke ones. One uniform shape per entity is consistent but conveys less domain intent than a named, purpose-built endpoint. The filter-key syntax and operator names are learned once across the API rather than read off each endpoint.
  • Opting out means overriding, not abandoning. All seven reads and both writes are virtual. A controller that needs bespoke behavior overrides the specific action and keeps the rest, but the five default reads are opt-out, not opt-in: you inherit them whether or not you wanted every route. Only the cursor page and the change feed run the other way, absent until a controller carries their marker.

Apply this even without MMCA

The pattern ports to any stack where you expose more than a handful of CRUD resources:

  1. Put the CRUD shape on a generic base and close the type parameters per entity. The verbs, routes, and response shapes belong in one place, inherited, not copied. A new entity should be a few lines, not a new file of near-duplicate actions.
  2. Parse filter, sort, and page once into a typed structure. A single model binder that turns a structured query string into a (property, operator, value) dictionary beats per-action parameter lists that drift in name and semantics.
  3. Filter through a per-type strategy registry with validated operators. Resolve a strategy by the property's CLR type and validate the operator up front. That is dynamic without being arbitrary, and it keeps free-form expression evaluation (the injection risk) out of the engine.
  4. Always cap an unpaginated read. A last-resort Take(N) ceiling in the query pipeline, independent of any API page-size clamp, means a forgotten pagination clause degrades to a bounded result instead of a database-pinning full scan.
  5. Mediate the wire contract through a DTO and a name map. Projecting entities straight to JSON couples your API to your schema. A DTO plus a DTO-to-entity property map lets a column rename stay an internal change instead of a breaking one.

What we covered: why hand writing a list/paged/by-id CRUD controller plus ad-hoc filter/sort/paging parsing per entity is the bulk of a monolith's boilerplate and drifts in shape, and how MMCA.Common answers with two base classes (EntityControllerBase for the five default reads plus two opt-in ones, AggregateRootEntityControllerBase for idempotent create and delete, with the base resolving the create response's Location itself) over a shared EntityQueryService and EntityQueryPipeline, plus a bounded OData-lite query contract: sparse fields projection, QueryFilterModelBinder plus per-type IFilterStrategy filtering with up-front validation, sort, an X-Pagination header with a MaxPageSize clamp, a streamed CSV export bounded by MaxExportRows, a MaxUnboundedResultLimit ceiling, and a two-path include strategy, composing with manual DTO mapping (ADR-001), navigation populators (ADR-002), the Result edge (ADR-013), and idempotency (ADR-017); an opt-in keyset cursor page behind [SupportsCursorPaging] with one validated sort column, an Id tie-break, an opaque cursor and no total (ADR-145); and hand-written SQL held to the same parameterize-the-value rule by the FormattableString-only IRawSqlQueryExecutor and a fitness test that bans EF's raw-string members (ADR-125).

Next in the series: resource-ownership authorization, the row-level axis that decides not just what a caller may do but which rows they may touch.

MMCA.Common is Apache-2.0 licensed and open source. Star the repo, read the 2-minute ADR-034 behind this pattern, or dotnet add package MMCA.Common.API and try it.

Tags: .NET, C Sharp, Web API, Software Architecture, Programming