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

Onboarding guide

3. Querying: Specifications, Filtering & the Entity Query Service

What this group covers. Every read in MMCA.Common and ADC ("list the published events", "get session 42", "the speakers in Atlanta, page 3, sorted by name, with only the name and bio fields") flows through one reusable read engine. This chapter is the read side of CQRS (the command/query split is introduced in primer §2): side-effect-free queries that turn query-string knobs into WHERE, ORDER BY, OFFSET, and SELECT clauses the database executes, then shape the rows down to the fields the caller asked for. There is no per-entity repository method and no hand-rolled IQueryable plumbing in each controller: add an entity and it inherits filtering, sorting, paging, sparse-fieldset projection, and eager loading of navigations. The trade-offs behind that generic read surface (dynamic filtering, sparse fieldsets, per-type filter strategies, the pagination header, the unbounded-result ceiling, and the two-path include strategy) are recorded in ADR-034; the repository-plus-specification contract underneath it, including the richer QuerySpecification shape and the projection pushdown described below, is ADR-055. Both compose with manual DTO mapping (ADR-001), navigation populators (ADR-002), and the Result pattern at the edge (ADR-013).

Three sub-systems cooperate here, and it pays to hold them apart from the start:

  1. The Specification pattern (Domain layer): the type-safe, programmer-authored predicate. A compiled Expression<Func<TEntity, bool>> that usually carries an authorization or business scope the caller must not be able to override ("only published events", "only the answers I submitted").
  2. Dynamic filtering, sorting, and field selection (Application layer): the string-driven, user-authored shaping behind ?filter=...&sort=...&fields=.... Untrusted input that must be validated against the entity's real properties before it reaches the database.
  3. The query pipeline and the entity query service (Application layer): the orchestrator that composes both, decides how to load navigations given the data source's JOIN capabilities, runs the query, and packages the result with pagination metadata.

The split matters: specifications are trusted and live with the domain, dynamic filters are untrusted and are validated, capped, and reflection-cached at the application boundary.

The Specification pattern, the trusted predicate

ISpecification<TEntity, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Domain/Interfaces/ISpecification.cs:12) exposes two faces of one rule: a Criteria expression tree that EF Core translates to SQL, so the filter runs in the database rather than in memory after a full-table load (ISpecification.cs:17), and IsSatisfiedBy(entity) for in-memory evaluation (ISpecification.cs:22). The abstract base Specification<TEntity, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:15) leaves Criteria abstract (Specification.cs:23), compiles it lazily on first use, and caches the delegate in a private field (Specification.cs:27, Specification.cs:32), so repeated in-memory checks do not recompile the tree.

The three combinators, AndSpecification<TEntity, TIdentifierType> (Specification.cs:80), OrSpecification<TEntity, TIdentifierType> (Specification.cs:106), and NotSpecification<TEntity, TIdentifierType> (Specification.cs:131), each delegate to the internal SpecificationComposer (Specification.cs:150) and cache the composed expression in a per-instance _criteria field rather than rebuilding it on every Criteria read (Specification.cs:87-92, Specification.cs:111-116, Specification.cs:133-137), because the pipeline reads Criteria at least once per request. Combine (Specification.cs:197) takes the left lambda's own parameter (Specification.cs:209), rebinds the right-hand body onto it, and joins the two with Expression.AndAlso or Expression.OrElse before closing the lambda (Specification.cs:211-215); Negate (Specification.cs:223) wraps the body in Expression.Not while keeping the inner lambda's parameter (Specification.cs:231-233). The rebinding is done by ParameterReplacer (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/ParameterReplacer.cs:24), an ExpressionVisitor whose static Replace short-circuits when the two parameters are already the same instance (ParameterReplacer.cs:34, ParameterReplacer.cs:40) and whose VisitParameter swaps the rest (ParameterReplacer.cs:44). Composing by substitution rather than Expression.Invoke is a deliberate portability decision: an InvocationExpression survives into the query tree and several providers (Cosmos among them) refuse to translate one, so an ANDed specification failed on exactly the engines the framework is meant to be portable across (Specification.cs:65-70, ParameterReplacer.cs:12-16). The visitor is internal and reaches the Application layer through InternalsVisibleTo so the cross-source builder shares one copy rather than carrying its own (ParameterReplacer.cs:18-23). SpecificationExtensions (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/SpecificationExtensions.cs:36) puts a fluent face on those three, as extension<TEntity, TIdentifierType> members (SpecificationExtensions.cs:38) exposing And (SpecificationExtensions.cs:54), Or (SpecificationExtensions.cs:74), and Not (SpecificationExtensions.cs:91), so a composed predicate reads left to right instead of inside out.

Concrete specifications are how a controller scopes a query to allowed data without trusting the request to do it. ADC has two, both one-liners: PublishedEventSpecification is e => e.IsPublished (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Events/Specifications/PublishedEventSpecification.cs:11, criteria at PublishedEventSpecification.cs:14), and PublicSessionStatusSpecification allows the public session-status list (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/Specifications/PublicSessionStatusSpecification.cs:21), exposing its predicate as a public static readonly expression (PublicSessionStatusSpecification.cs:24) so the cross-source filter and the visible-session id resolver share one definition rather than each re-deriving BR-49 (Criteria simply returns it at PublicSessionStatusSpecification.cs:28). The framework also ships one ready-made scope: OwnedByUserSpecification<TEntity, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/OwnedByUserSpecification.cs:20) filters on the audit field CreatedBy as the ownership marker (OwnedByUserSpecification.cs:29-30), and its constraint is deliberately the concrete AuditableBaseEntity<TIdentifierType> rather than an IAuditableEntity interface, because a member access declared on an interface is not guaranteed to map to the entity's audit column and the criteria must stay EF-translatable (OwnedByUserSpecification.cs:12-16). ADC's question-answer controllers are its callers, and they show the intended shape: an organizer gets null (no scoping at all), everyone else gets the specification bound to their own user id (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventQuestionAnswersController.cs:101, and the same pair at SessionQuestionAnswersController.cs:101). This is [Rubric §4, Domain-Driven Design] (the rule is a first-class, reusable domain object) and [Rubric §2, Design Patterns] (a textbook Specification), with a [Rubric §11, Security] overtone: an authorization predicate is server-supplied criteria the client cannot tamper with.

Two members round the family out for polyglot persistence (ADR-018). InlineSpecification<TEntity, TIdentifierType> (Specification.cs:45) wraps an already-composed Criteria expression as a first-class specification (Specification.cs:51-52), for predicates built at runtime where no hand-written class exists. The static CrossSourceSpecification (MMCA.Common/Source/Core/MMCA.Common.Application/Specifications/CrossSourceSpecification.cs:26) builds the cross-source filter: when a dependent entity references a principal that lives in a different physical data source (database-per-service, ADR-006), a navigating predicate like s => s.Event.IsPublished cannot be translated, so BuildAsync (CrossSourceSpecification.cs:43) first projects the matching principal keys from the principal's own source through the read repository's GetProjectedAsync (CrossSourceSpecification.cs:59-60), materializes them once (CrossSourceSpecification.cs:64), and returns an InlineSpecification (CrossSourceSpecification.cs:66) whose body is an Enumerable.Contains(keys, dependent.ForeignKey) call that translates to IN or ARRAY_CONTAINS (CrossSourceSpecification.cs:80-85). An optional local predicate on the dependent's own columns is rebound onto the foreign-key selector's parameter by the shared ParameterReplacer (CrossSourceSpecification.cs:92) and ANDed in (CrossSourceSpecification.cs:93), again without Expression.Invoke so the combined predicate stays translatable on every provider (CrossSourceSpecification.cs:89-91). The doc comment is explicit about the limit: the keys are materialized and carried in the predicate, so the shape fits bounded principal sets (CrossSourceSpecification.cs:18-19). The list still reaches the database as a query parameter, never as inlined literals: the Contains call reads it through a member access on the private KeyCarrier<TPrincipalId> (CrossSourceSpecification.cs:105, the access at CrossSourceSpecification.cs:84), a one-property holder that gives the keys the shape a captured local has, which EF Core extracts as a parameter (CrossSourceSpecification.cs:100-101, CrossSourceSpecification.cs:78-79). A bare constant list made EF emit IN (1, 2), one distinct SQL text, query plan, and compiled-query cache entry per key set, and the key set changes whenever the principal set does (CrossSourceSpecification.cs:20-23). ADC uses it in production on both of its Session reads, each passing PublicSessionStatusSpecification.StatusCriteria as the local predicate: GetPublicSessionFilterHandler returns the specification as a query result (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/GetPublicSessionFilter/GetPublicSessionFilterHandler.cs:29-34), and PublicConferenceVisibility uses the same criteria to resolve the visible session ids so a session hidden from the session list cannot stay reachable through a speaker or junction read (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Common/PublicConferenceVisibility.cs:63-68). The convention this exists to serve is guarded by an opt-in fitness rule, ArchitectureRules.SpecificationsDoNotNavigateToOtherEntities (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Domain/ArchitectureRules.Specifications.cs:24), which analyzes only the parameterless specifications it can instantiate (ArchitectureRules.Specifications.cs:37-38) and is exposed to repos as the single-fact base SpecificationConventionTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Domain/SpecificationConventionTestsBase.cs:10, the fact at SpecificationConventionTestsBase.cs:15-16), which is [Rubric §14, Testability] applied to an architectural rule.

QuerySpecification, a whole read in one object

A plain specification is only a predicate, which leaves includes, ordering, paging, and tracking to be threaded through every layer as loose arguments. QuerySpecification<TEntity, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/QuerySpecification.cs:43) carries them instead. State is exposed read-only (OrderBy at QuerySpecification.cs:59, IncludePaths at QuerySpecification.cs:65, Skip and Take at QuerySpecification.cs:68 and QuerySpecification.cs:71, AsTracking at QuerySpecification.cs:77, IgnoreQueryFilters at QuerySpecification.cs:87) and assembled through protected builder methods a derived specification calls from its constructor: AddOrderBy (QuerySpecification.cs:95), AddInclude (QuerySpecification.cs:107, which ignores blanks and duplicates at QuerySpecification.cs:109-113), ApplyPaging (QuerySpecification.cs:122, both values floored at zero at QuerySpecification.cs:124-125), WithTracking (QuerySpecification.cs:132), and WithSoftDeleted (QuerySpecification.cs:138). Two design notes are worth carrying forward. The base chain stays QuerySpecification over Specification on purpose, because the fitness rule above keys on that base-type prefix and on a property literally named Criteria (QuerySpecification.cs:29-34). And WithSoftDeleted drops the named SoftDelete global query filter and only that one, so a specification asking for deleted rows can never reach another tenant's data (QuerySpecification.cs:79-86). Each ordering key is an OrderExpression (QuerySpecification.cs:155), a record of an untyped LambdaExpression plus a descending flag, declared top-level rather than nested inside the generic class because a nested type is a different type per closed generic, which would stop the repository evaluator from handling an ordering list generically (QuerySpecification.cs:145-149).

That object is consumed on the persistence side, not by the pipeline in this chapter. The repository's ListAsync(specification) (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Persistence/IRepository.cs:262) takes any ISpecification, and SpecificationEvaluator (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/SpecificationEvaluator.cs:21) applies the Criteria always (SpecificationEvaluator.cs:46) and the rest only when the instance is a QuerySpecification (SpecificationEvaluator.cs:56-66). Tracking and soft-delete scope are deliberately not applied there: those choose the base queryable, which only the repository can do, in EFReadRepository<TEntity, TIdentifierType>'s BaseQueryFor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:573-581, rationale at EFReadRepository.cs:567-572), with the concrete reads at EFReadRepository.cs:599 (ListAsync), EFReadRepository.cs:612 (the projecting overload, which selects last so a paged specification pages the rows it means to, EFReadRepository.cs:620-624), and EFReadRepository.cs:118 (FirstOrDefaultAsync, which keeps the full shape because "first" is only meaningful against a defined order, EFReadRepository.cs:124-125). Aggregate reads (count, exists) pass applyShape: false so counting does not join in includes or count "page 3 of the matches" (SpecificationEvaluator.cs:30-35, the call sites at EFReadRepository.cs:454 and EFReadRepository.cs:664). Includes go through one shared helper that also opts the query into split-query mode whenever any include targets a collection navigation (SpecificationEvaluator.cs:87, the decision at SpecificationEvaluator.cs:103), so the string-include path and the specification path cannot drift apart (SpecificationEvaluator.cs:77-82, the delegation at EFReadRepository.cs:560-563).

Dynamic filtering, one Strategy per CLR type

User filters arrive as a Dictionary<string, (string Operator, string Value)>, property name to operator key plus raw string value, parsed from the query string by QueryFilterModelBinder at the API edge. The binder keeps every complete entry and only mirrors the cap (MMCA.Common/Source/Presentation/MMCA.Common.API/ModelBinders/QueryFilterModelBinder.cs:34); the cap itself is QueryFilterService.MaxFilters = 50 (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:34), and a request over it is refused whole as Filter.TooMany before any key is resolved, because dropping the surplus would silently widen the result set past what the caller asked for (QueryFilterService.cs:192-197, rationale at QueryFilterService.cs:27-33). Turning ("Name", "CONTAINS", "blazor") into a .Where() clause depends entirely on the property's CLR type, so instead of one large switch each type gets an IFilterStrategy (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/IFilterStrategy.cs:8) declaring an Apply method (IFilterStrategy.cs:19), the operator set it supports, which ValidateFilters checks before the strategy is applied (IFilterStrategy.cs:25, with no default: every strategy declares its own), and a CanParseValue predicate that defaults to true (IFilterStrategy.cs:45). The interface is internal, because the strategy table in QueryFilterService is fixed and only the framework's own strategies implement it (IFilterStrategy.cs:3-7). CanParseValue exists because Apply fails open: a strategy that cannot parse a value silently returns the query unfiltered, so ?filter=id:equals:abc would return the whole result set instead of no matches (IFilterStrategy.cs:34-39). Validating the value up front turns that into a 400, and the default of true serves the one strategy whose Apply never parses the value into another type, the e-mail strategy, which compares the raw text (IFilterStrategy.cs:40-43).

The built-in strategy classes each declare SupportedOperators as a FrozenSet: StringFilterStrategy (StringFilterStrategy.cs:12, operators at StringFilterStrategy.cs:14-18: CONTAINS, NOT CONTAINS, EQUALS, NOT EQUALS, STARTS WITH, ENDS WITH, IS EMPTY, IS NOT EMPTY, IN), the generic NumericFilterStrategy<TNumber> (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/NumericFilterStrategy.cs:23, constrained to struct, INumber<TNumber> at NumericFilterStrategy.cs:24), one type closed three times in the registry over int, long, and decimal (QueryFilterService.cs:67-74) so a new numeric operator is written once (NumericFilterStrategy.cs:9-12), with one operator set (equality, the four comparisons, IN, an inclusive BETWEEN range, and the two presence checks, at NumericFilterStrategy.cs:27-32) and values parsed through INumber<TNumber>.TryParse with the invariant culture (NumericFilterStrategy.cs:54-55), which keeps each type's own default number style so the DSL means the same thing under every request culture (NumericFilterStrategy.cs:15-18), DateTimeFilterStrategy (DateTimeFilterStrategy.cs:13: IS, IS NOT, IS AFTER, IS ON OR AFTER, IS BEFORE, IS ON OR BEFORE, the two presence checks, IN, and BETWEEN at DateTimeFilterStrategy.cs:17-22, parsed with CultureInfo.InvariantCulture at DateTimeFilterStrategy.cs:15), BoolFilterStrategy (BoolFilterStrategy.cs:12: IS plus the two presence checks, BoolFilterStrategy.cs:14-17), and GuidFilterStrategy (GuidFilterStrategy.cs:13: EQUALS, NOT EQUALS, IN, and the two presence checks at GuidFilterStrategy.cs:15-18; GUIDs have no ordering, so no comparisons). Every value-typed strategy implements CanParseValue by delegating to one shared rule (NumericFilterStrategy.cs:35-36, DateTimeFilterStrategy.cs:25, BoolFilterStrategy.cs:20, GuidFilterStrategy.cs:21). StringFilterStrategy declares its own, narrower check: every string operator accepts any value, the empty string for EQUALS included, and only an IN list with no usable item is refused, because it would otherwise fail open and return the unfiltered set where every value-typed strategy refuses the same input (StringFilterStrategy.cs:26-27, rationale at StringFilterStrategy.cs:22-24). That shared rule lives in the internal FilterValueParser (FilterValueParser.cs:10): CanParse (FilterValueParser.cs:55) says presence checks ignore the value, IN needs at least one item and every item to parse, BETWEEN needs exactly two bounds, and every other operator needs the single scalar to parse (FilterValueParser.cs:60-66). The IN rule (EveryItemParses at FilterValueParser.cs:78) deliberately does not reuse the lenient list parser: skipping unparseable items let "1,abc" validate, and the strategy then silently narrowed the filter to the items that happened to parse (FilterValueParser.cs:72-77). BETWEEN gets its own stricter check (FilterValueParser.cs:98) that keeps empty and unparseable segments in play, because dropping them let "5,abc,10" and "5,,10" validate as a two-bound range and the strategies then applied a pair the caller never asked for (FilterValueParser.cs:92-97). The same class decodes the lists at apply time: because validation refuses any unparseable item, a validated list always parses whole, and ParseList<T> skips an unparseable entry only for a caller that applies filters without validating them (FilterValueParser.cs:3-9, the method at FilterValueParser.cs:19, the if (parse(part) is { } parsed) guard at FilterValueParser.cs:28), and ParseStringList splits on comma, trimming and dropping empty entries (FilterValueParser.cs:36). One more strategy is never registered up front because it cannot be: StronglyTypedIdFilterStrategy<TSelf, TValue> (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/StronglyTypedIdFilterStrategy.cs:24) is internal sealed and generic over an identifier wrapper and its wrapped primitive (StronglyTypedIdFilterStrategy.cs:25-26), so one closed strategy exists per identifier type a model declares. The client still sends the primitive (filters[Id].value=42); the strategy parses it into the wrapper and compares wrapper to wrapper, so EF Core's value converter turns both sides into the same primitive column and adopting a wrapper (ADR-115) does not change the filter DSL a client speaks (StronglyTypedIdFilterStrategy.cs:10-13, the parse at StronglyTypedIdFilterStrategy.cs:49-50). Only the equality family is supported, EQUALS, NOT EQUALS, IN, and the two presence checks (StronglyTypedIdFilterStrategy.cs:28-31, applied at StronglyTypedIdFilterStrategy.cs:38-47): a record struct declares == and != and nothing else, so there is no > to build a range from, and an unsupported operator is a 400 from validation rather than a silently widened result set (StronglyTypedIdFilterStrategy.cs:14-20). The non-generic companion StronglyTypedIdFilterStrategy.TryCreate (StronglyTypedIdFilterStrategy.cs:78) closes the generic at runtime from StronglyTypedId.TryDescribe (StronglyTypedIdFilterStrategy.cs:80-84), which is what lets a consumer adopt wrappers with no per-identifier registration (QueryFilterService.cs:431-437).

The one built-in keyed to a value object rather than a primitive is EmailFilterStrategy (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/ValueObjects/EmailFilterStrategy.cs:27), registered against the Common Email type (QueryFilterService.cs:77) so a grid's Email column filters on an entity that stores the value object. It speaks the string vocabulary minus IN (EmailFilterStrategy.cs:35-39) and, alone among the built-ins, builds its predicate as an expression tree rather than a Dynamic LINQ string (EmailFilterStrategy.cs:42-71), because the address has two translations. The value object is mapped through a value converter (EmailValueConverter) onto one string column, and EF Core cannot translate member access into a converted value, so e.Email.Value.Contains(x) fails at query time; against a database the predicate therefore reads the column as (string)(object)e.Email, whose two casts EF Core strips to compare the stored string itself, while LINQ to Objects, which cannot make that cast, reads Email.Value behind a null guard (EmailFilterStrategy.cs:13-20, the switch on query.Provider is EnumerableQuery at EmailFilterStrategy.cs:56-59, the guards at EmailFilterStrategy.cs:95-100 and EmailFilterStrategy.cs:116-118). The choice follows the query's provider, never configuration. A dotted path is walked to its leaf and rejected unless that leaf is an Email (EmailFilterStrategy.cs:74-89). The needle is folded to lower case character by character with the invariant culture, the form Email.Create stores, so a match does not depend on the database collation (EmailFilterStrategy.cs:23-24, ToStoredCase at EmailFilterStrategy.cs:125-132), and it is wrapped in the private Needle record (EmailFilterStrategy.cs:139) and read through a member access (EmailFilterStrategy.cs:104), which EF Core turns into a query parameter instead of an inlined literal (EmailFilterStrategy.cs:134-137): the same plan-cache concern the next paragraph describes, settled here without Dynamic LINQ.

Every other clause is built through System.Linq.Dynamic.Core string predicates with parameter placeholders (@0), never string-concatenated values, and every call site passes the one shared DynamicQueryConfig.Parameterized parsing config (DynamicQueryConfig.cs:18, the instance at DynamicQueryConfig.cs:21-24). That flag is not cosmetic: Dynamic LINQ defaults UseParameterizedNamesInDynamicQuery to false, which turns each @0 into a ConstantExpression that EF inlines, so one filter value produces one distinct SQL string, one SQL Server plan-cache entry per value, and an EF compiled-query cache miss on every request (DynamicQueryConfig.cs:8-16). With the flag on the value is reached through a member access and EF parameterizes it, and QueryParameterizationTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/QueryParameterizationTests.cs:26) is the regression guard, the only test in the suite that inspects the emitted SQL. This is [Rubric §12, Performance & Scalability] hiding inside a one-property config object.

The static QueryFilterService (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:25) is the registry and dispatcher. It holds the built-ins in a FrozenDictionary<Type, IFilterStrategy> fixed at type initialization, both the value type and its Nullable<> form, plus the Email value object once (QueryFilterService.cs:60-78), keeps a dedicated string instance used whenever the resolved value type is string, a flat property or a dotted path whose leaf is one (QueryFilterService.cs:86-90), and keeps strongly-typed-identifier strategies apart in a ConcurrentDictionary keyed by the model's CLR types (QueryFilterService.cs:80-84). There is no runtime registration call: the filterable types are the built-ins plus whatever identifier wrappers the model declares. ResolveStrategy (QueryFilterService.cs:438) is the three-step dispatch behind both phases: the string instance for string (QueryFilterService.cs:440-441), the built-in table next (QueryFilterService.cs:443-444), and the strongly-typed-identifier fallback last, built on first use and memoized so that dictionary grows with the number of CLR types the model declares, never with client input (QueryFilterService.cs:446-448, rationale at QueryFilterService.cs:431-437). Ahead of both phases, NormalizeOperator puts every operator into the vocabulary the strategies speak: upper case, so a grid's lower-case "contains" matches, and the comparison symbols a grid's number column sends (=, !=, >, >=, <, <=) mapped onto their word forms, so every strategy accepts both spellings without a client translating (QueryFilterService.cs:461-470, rationale at QueryFilterService.cs:451-458). An aliased key such as "Name~search" resolves as its bare property and ANDs with that property's own filter (QueryFilterService.cs:120-122). Reflection is case-insensitive and memoized per (entity type, property name) but hits only (the cache at QueryFilterService.cs:57-58, LookupProperty at QueryFilterService.cs:367, the case-insensitive lookup at QueryFilterService.cs:372-373): the probed names come from the client's query string, so caching misses would let any caller grow a never-evicted static dictionary simply by filtering on names that do not exist, while the request still gets a clean 400; a miss costs one reflection lookup instead, which the MaxFilters cap bounds (QueryFilterService.cs:345-352). A hit is stored under the property's canonical name (QueryFilterService.cs:377) and the key compares names ignoring case through the private TypeAndNameIgnoreCaseComparer (QueryFilterService.cs:386, the comparison at QueryFilterService.cs:390-395), so every client casing of a real property lands on one entry; keyed by the probed spelling, each of the 2^N casings of an N-letter name minted its own entry (QueryFilterService.cs:51-55). What remains is capped at MaxPropertyCacheEntries = 512, past which a hit is resolved by reflection per request rather than admitted (QueryFilterService.cs:42, rationale at QueryFilterService.cs:36-41, the check at QueryFilterService.cs:376). One shared resolver, ResolvePropertyInfo (QueryFilterService.cs:354), backs both phases so they cannot disagree about what resolves; when they did, a plain rename entry passed validation and was then silently dropped, returning an unfiltered 200 (QueryFilterService.cs:339-344). A dotted path like "Category.Name" is walked segment by segment to its leaf type by ResolveFilterValueType (QueryFilterService.cs:410), so the leaf's own strategy validates the operator instead of every nested path defaulting to the string strategy (QueryFilterService.cs:271-276). A path whose leaf cannot be reached is failed closed rather than guessed at: validation rejects it as an unknown property (QueryFilterService.cs:281-289) and application skips it (QueryFilterService.cs:142-144), because letting Dynamic LINQ meet an unexpressible filter turns a bad request into a 500 (QueryFilterService.cs:403-409).

What a client may name at all is decided before any of that, and the allow-list is the response contract, not the entity. QueryFieldContract (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryFieldContract.cs:34) is a frozen, case-insensitive set of names: For<TContract>() reflects a DTO's public instance properties once per type and caches them (QueryFieldContract.cs:56, QueryFieldContract.cs:64, the cache at QueryFieldContract.cs:44, the set built at QueryFieldContract.cs:70-73), and ForNames narrows it to an explicit, server-authored list for a DTO that declares a field the response redacts per role (QueryFieldContract.cs:83). AllowsClientKey admits a name only when the contract declares it and it carries no dot, so a caller can neither address a column no DTO exposes nor walk the object graph (QueryFieldContract.cs:103-106), while the static IsWithinNavigationDepth caps any resolved path, server-authored ones included, at MaxNavigationDepth = 3 segments (QueryFieldContract.cs:42, QueryFieldContract.cs:115-137). The reasoning is recorded on the type (QueryFieldContract.cs:12-32): an entity carries columns the response never does (audit fields, credential material, columns a mapper redacts per role), ordering a public list by one of them leaks its total order and a STARTS WITH filter over one turns a list endpoint into a character-by-character oracle, and an unbounded dotted path is another LEFT JOIN per segment in the emitted SQL. Map entries stay the escape hatch, because the server wrote them. In the filter service that gate is IsAdmissibleKey (QueryFilterService.cs:224): depth first, then map-authored or contract-declared (QueryFilterService.cs:230-233, rationale at QueryFilterService.cs:210-222). This is [Rubric §11, Security] in one small type.

The two phases and their ordering are the rest of the security story. ValidateFilters (QueryFilterService.cs:181, one signature whose fieldContract argument is always passed, null being the explicit opt-out to the entity-only check that is correct only for server-authored keys, QueryFilterService.cs:176-179) runs before the query. Past the whole-request Filter.TooMany check (QueryFilterService.cs:191-198) it returns a Result carrying every Error it found: Filter.Property.NotFound three times over, for a key the contract refuses (QueryFilterService.cs:249-255), a property the entity does not have (QueryFilterService.cs:261-266), and a dotted path whose leaf does not resolve (QueryFilterService.cs:283-289); then Filter.Type.NotSupported (QueryFilterService.cs:295-300), Filter.Operator.NotSupported (QueryFilterService.cs:482-487), and Filter.Value.Invalid (QueryFilterService.cs:328-332), the last suppressed when the operator itself was already rejected so one mistake does not produce two errors (QueryFilterService.cs:321-324). A bad filter is therefore a validation failure, not a SQL exception and not a silently widened result set. ApplyFilters (QueryFilterService.cs:109, likewise with deliberately no overload that omits the contract, so the choice is visible at every call, QueryFilterService.cs:103-107) then builds the actual .Where() chain, resolving the DTO name through the property map first (QueryFilterService.cs:125-126), running the same admissibility gate so a caller that skipped validation cannot reach the Dynamic LINQ builder with a refused key (QueryFilterService.cs:131-132, the note at QueryFilterService.cs:128-130), and skipping any property it cannot resolve (QueryFilterService.cs:136-137). A flat client key is applied under the property's declared name, so the Dynamic LINQ member access never depends on how the client cased it, while a server-authored map entry is applied verbatim because it may be an expression rather than a member name (QueryFilterService.cs:148-155). Strategy dispatch plus allow-listing untrusted input against the response contract is [Rubric §2, Design Patterns] and [Rubric §11, Security] together.

Sorting, sparse fieldsets, and paging arithmetic

QueryFieldService (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryFieldService.cs:16) owns the rest of read shaping. ApplySorting (QueryFieldService.cs:168, one signature that always takes the fieldContract, at QueryFieldService.cs:173, a null being the explicit opt-out for server-authored names) resolves a DTO sort name through the server-authored map, and for a name the map does not cover it consults the response contract before the entity is reflected over at all: a column the DTO does not declare resolves to nothing (ResolveSortExpression at QueryFieldService.cs:306, the contract gate at QueryFieldService.cs:323-326, the entity lookup that only runs past it at QueryFieldService.cs:329-331), and the query falls back to the optional default sort instead (QueryFieldService.cs:186-192). Whatever the source, the resolved path is refused past QueryFieldContract.MaxNavigationDepth (QueryFieldService.cs:334). That guard is deliberate and documented on the overload (QueryFieldService.cs:299-304): a client-supplied string can never reach Dynamic LINQ to order by nested paths, nor order a public page by a column the response never carries. The same contract gates fields: ValidateSingleField checks the server-authored map first, capping its depth, then the response contract, and only then the entity's own property set (QueryFieldService.cs:580, the map branch at QueryFieldService.cs:589-601, the contract branch at QueryFieldService.cs:603-616), reached through a third Validate<TEntity> overload that takes the contract (QueryFieldService.cs:503). The sort column is validated by ValidateSortColumn (QueryFieldService.cs:523) with exactly the rules ApplySorting applies: a comma-separated list is refused because sorting honors one column, and the single trimmed name then goes through the same map, contract, and entity check (QueryFieldService.cs:531-541, rationale at QueryFieldService.cs:511-516). Map entries, being server-authored, may be expressions: ADC sorts speakers by FullName through an entry that concatenates first and last name (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/SpeakerEntityQueryService.cs:30, wired in by overriding the map at SpeakerEntityQueryService.cs:51). The method also takes an optional tieBreakProperty appended as a final ascending key (QueryFieldService.cs:175, applied by BuildOrdering at QueryFieldService.cs:342, and used alone when no valid sort column was given at QueryFieldService.cs:194-196). It exists because Skip/Take over a non-total ORDER BY is undefined: rows sharing a sort value can come back in a different order per statement, so the same row appears on two consecutive pages while another appears on neither, from data that never changed (QueryFieldService.cs:152-166). The append is repeated-key aware, skipped when the caller already sorted by that very column (QueryFieldService.cs:347-348, rationale at QueryFieldService.cs:338-340). The list read sorts through one more entry, the internal ApplyListSorting (QueryFieldService.cs:214): the request's sort column when it resolves, otherwise a server-authored default ordering (a specification's OrderBy, applied key by key as typed expressions), otherwise the tie-break alone, so a specification's ordering is a default and never a second key layered under the client's (QueryFieldService.cs:199-204, the branch at QueryFieldService.cs:223-230). The tie-break is again skipped when the default ordering already sorts by that key, because SQL Server rejects a column repeated in an ORDER BY (QueryFieldService.cs:232-238).

ApplyFieldSelection (QueryFieldService.cs:362) builds a MemberInit Select expression so a fields=name,bio request pulls only those columns from the database ([Rubric §12, Performance & Scalability]), restricted to writable properties because the projection needs setters (QueryFieldService.cs:425-434, the CanWrite filter at QueryFieldService.cs:430). The compiled lambda is cached per (entity type, normalized field set) (QueryFieldService.cs:370, cache at QueryFieldService.cs:423), and a null is cached on purpose to record "this field set projects nothing writable" so the miss is not recomputed per request (QueryFieldService.cs:412-414). ShapeData and ShapeCollectionData (QueryFieldService.cs:82, QueryFieldService.cs:103) produce the wire shape: an ExpandoObject (or a list of them) holding only the requested fields under camelCase keys. To make that cheap on large result sets the service caches a per-type array of PropertyAccessor (QueryFieldService.cs:49), a private readonly record struct bundling each property's name, its precomputed camelCase key, and a compiled Func<object, object?> getter built with Expression.Lambda(...).Compile() rather than PropertyInfo.GetValue (QueryFieldService.cs:53, built at QueryFieldService.cs:55-72); the field-filtered subset is cached again per field set (QueryFieldService.cs:697, QueryFieldService.cs:703), under an order- and case-insensitive key so name,id and Id, Name share one entry (QueryFieldService.cs:744-745).

Both field-set caches are bounded, and the reason is the same one that shapes the filter cache. Their key is half client-supplied, so an entity with N properties admits up to 2^N distinct subsets and a caller could grow either dictionary by permuting the list (QueryFieldService.cs:18-38). The cap is a const int MaxCacheEntries = 512 per cache (QueryFieldService.cs:39), with deliberately no LRU: past the cap ApplyFieldSelection skips server-side projection rather than admitting another key (QueryFieldService.cs:382-383, and the response is unchanged because shaping still trims the payload), and GetShapedAccessors filters per request instead (QueryFieldService.cs:722-723), which is a scan over an already-compiled accessor array rather than an expression rebuild. Validation mirrors the filter side: Validate<TEntity> rejects unknown field names and (when shaping) read-only properties (QueryFieldService.cs:461 and the map-aware overload at QueryFieldService.cs:503, shared body at QueryFieldService.cs:552), and ValidateSortDirection accepts only asc or desc (QueryFieldService.cs:647). Paging arithmetic is small enough to look trivial and is not, which is why it has its own type: PagingMath.Clamp (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/PagingMath.cs:33) clamps the page size into [1, maxPageSize] and the page number to at least 1 (PagingMath.cs:38-39), computes the offset in 64-bit (PagingMath.cs:41), and for a page beyond the reachable offset range returns Skip = 0, Take = 0, materializing the empty page that page genuinely holds (PagingMath.cs:43-45). A 32-bit (pageNumber - 1) * pageSize overflows and wraps negative near int.MaxValue, and SQL Server rejects a negative OFFSET outright, so the request would surface as a 500 instead of an empty page (PagingMath.cs:8-12). The result is a PageWindow (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/PageWindow.cs:23), a readonly record struct of the page number and page size actually served plus the Skip/Take pair that reads them. One record carries both halves so a caller reports exactly the page it read: the pagination metadata takes the page number and size, the query takes Skip and Take, and neither re-derives the clamp (PageWindow.cs:10-12). On the unreachable-page sentinel the window's PageSize stays the clamped request while Take is 0, so the metadata never advertises a zero page size (PageWindow.cs:17-20). The pipeline, the handlers that paginate their own queryable (the notification inbox and history reads), and the view-as grant stores all page through it, and callers must route through here rather than open-coding the multiply (PagingMath.cs:14-18).

The pipeline: two entity paths plus projection pushdown

IEntityQueryPipeline (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/IEntityQueryPipeline.cs:10) is the execution contract, implemented by the sealed EntityQueryPipeline (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:14), which talks to the database through the IQueryableExecutor abstraction rather than referencing EF Core from the Application layer ([Rubric §3, Clean Architecture]). Its inputs are bundled into EntityQueryParameters<TEntity> (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryParameters.cs:12), an immutable record carrying an optional Criteria (EntityQueryParameters.cs:15), the dynamic Filters, a server-authored DefaultOrdering used only when the request's sort column does not resolve (EntityQueryParameters.cs:20-25), sort column and direction, Fields, page number and size, the two include flags, the DTO-to-entity property map (defaulting to an empty FrozenDictionary, EntityQueryParameters.cs:52), and the response FieldContract the filter and sort resolvers gate client names against (EntityQueryParameters.cs:60). The pipeline itself never inspects the contract: it threads it into QueryFilterService.ApplyFilters and QueryFieldService.ApplySorting on every path it runs (ApplyFilters at EntityQueryPipeline.cs:79 and EntityQueryPipeline.cs:144, the one shared sort at EntityQueryPipeline.cs:250-261), so the projection path and the two entity paths enforce one allow-list. EntityQueryService leaves Criteria unset, because it scopes the base query through the repository instead (described below), so the pipeline applies Criteria only for a direct caller that sets it (EntityQueryPipeline.cs:75-76, EntityQueryPipeline.cs:140-141).

ExecuteAsync (EntityQueryPipeline.cs:41) runs a shared front half, ApplyIncludesCriteriaAndFilters (EntityQueryPipeline.cs:116): add every supported navigation as an .Include() through the executor (EntityQueryPipeline.cs:134-135), then apply any criteria and the dynamic filters before materializing anything (EntityQueryPipeline.cs:137-144) so the data source does as much of the work as possible. The comment above the include loop records the hard-won reason a child collection must load in split-query mode, annotated R24/§8: paginating a single-query collection include truncates child rows because EF applies Skip/Take to the JOIN-expanded set (EntityQueryPipeline.cs:129-130). The decision is not made in the pipeline: the executor's Include routes through the one split-query heuristic in SpecificationEvaluator.ApplyIncludes, so this path and the specification path cannot choose differently for the same include (EntityQueryPipeline.cs:131-133). It then branches on whether any requested navigation is unsupported (EntityQueryPipeline.cs:55). Path 1, server-side includes (EntityQueryPipeline.cs:204): sort (EntityQueryPipeline.cs:215), count before paging (EntityQueryPipeline.cs:223), Skip/Take (EntityQueryPipeline.cs:224), field-selection Select (EntityQueryPipeline.cs:234), materialize (EntityQueryPipeline.cs:235). Path 2, manual navigation (EntityQueryPipeline.cs:154), taken when a requested navigation crosses a physical data source and cannot be joined: sort and page at the database first (EntityQueryPipeline.cs:168, EntityQueryPipeline.cs:175), materialize the page (EntityQueryPipeline.cs:184), then invoke the navigationPopulator callback to batch-load those navigations in a second query (EntityQueryPipeline.cs:187), the INavigationPopulator<in TEntity> extension point of ADR-002, and apply field selection in memory afterwards (EntityQueryPipeline.cs:196). Every path sorts through one helper, ApplySorting (EntityQueryPipeline.cs:250), which hands QueryFieldService.ApplyListSorting the request's sort, the DefaultOrdering, and the entity key as the tie-break, the key only when the read is paginated (EntityQueryPipeline.cs:38, passed at EntityQueryPipeline.cs:261): an unpaginated read materializes one capped set in one statement, so it cannot suffer the split-across-pages incoherence, and adding an ORDER BY there would charge every unsorted list read for a sort nobody asked for (EntityQueryPipeline.cs:32-37).

ExecuteProjectedAsync (EntityQueryPipeline.cs:62) is the third path: for a read whose result type has a registered IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>, criteria, filters, sorting, and paging all run over entity rows (EntityQueryPipeline.cs:75-96) and the projection is applied last (EntityQueryPipeline.cs:102), so the provider pages exactly the rows it means to and selects only that page's columns. Nothing is materialized as an entity and no mapper runs. It handles server-side navigations only: there is no populator hook, because a projection cannot be post-processed row by row, so a query with cross-source includes must use ExecuteAsync instead, and navigation includes are not applied here at all because the projection itself decides what the provider joins and selects (IEntityQueryPipeline.cs:43-48, restated at EntityQueryPipeline.cs:98-101).

All three paths share one [Rubric §12, Performance & Scalability] safety ceiling: an unpaginated query is capped at MaxUnboundedResultLimit, a public const int defined as KeysetPageRequest.MaxPageSize so the offset and keyset entry points share one cap (EntityQueryPipeline.cs:25, rationale at EntityQueryPipeline.cs:16-24), which is 1000 (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:27), applied at EntityQueryPipeline.cs:95, EntityQueryPipeline.cs:181, and EntityQueryPipeline.cs:230), and a paginated call has its page size clamped to that same ceiling inside ApplyPaging, which delegates the offset arithmetic to PagingMath.Clamp (EntityQueryPipeline.cs:272-282). A direct service caller who forgets or oversizes paging therefore can never trigger an unbounded full-table load. The reported total for an unpaginated read is not simply the materialized count: CountUnpaginatedAsync (EntityQueryPipeline.cs:289) returns the materialized count only while it stays under the ceiling and issues a real COUNT otherwise (EntityQueryPipeline.cs:293-295), because at the cap the materialized number is the cap itself and reporting it told callers the set was exactly 1000 rows (EntityQueryPipeline.cs:284-288). Which navigations are eligible, and which path each takes, is decided by NavigationMetadataProvider (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:20) behind INavigationMetadataProvider (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/INavigationMetadataProvider.cs:9). BuildIncludes asks separately for FK references and child collections (NavigationMetadataProvider.cs:31), and the classifier reflects over the entity's public properties looking for NavigationAttribute (NavigationMetadataProvider.cs:74), unwraps ICollection<T> / IReadOnlyCollection<T> to find the target entity (NavigationMetadataProvider.cs:106), and asks IDataSourceService whether the two ends share a JOIN-capable source, sorting each NavigationPropertyInfo into the supported or unsupported bucket of NavigationMetadata (NavigationMetadataProvider.cs:96-99). Results are cached per (entity type, NavigationType) in an instance-level dictionary, not a static one, precisely so that a process hosting more than one data-source configuration (integration tests, for example) cannot share classifications across hosts (NavigationMetadataProvider.cs:28, rationale at NavigationMetadataProvider.cs:22-27).

The query service, the public face

IEntityQueryService<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityQueryService.cs:19) and its concrete EntityQueryService<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:35) are what controllers and handlers inject. The service is constructed from IUnitOfWork, the metadata provider, the pipeline, an IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType> (ADR-001), and an INavigationPopulator<TEntity> (EntityQueryService.cs:35-40), and it resolves its IReadRepository<TEntity, TIdentifierType> from the unit of work through a virtual property (EntityQueryService.cs:91). A second, six-argument constructor adds the optional IEntityDTOProjector (EntityQueryService.cs:73-81): it is a second constructor rather than an optional parameter because the Microsoft DI container has no notion of an optional dependency, so with two overloads it picks the longer one when a projector is registered and the shorter one when it is not (EntityQueryService.cs:57-64). Two virtual properties decide what a client may name against that service. FieldContract (EntityQueryService.cs:166) defaults to QueryFieldContract.For<TEntityDTO>(), so sort columns, filter keys, and fields resolve against the response contract rather than the entity; it is handed to the validators and packed into the pipeline parameters (EntityQueryService.cs:350-352, EntityQueryService.cs:385, EntityQueryService.cs:801). A subclass narrows it with QueryFieldContract.ForNames for a DTO that declares a field the mapper redacts per role, and returning null restores resolution against the entity as a deliberate, documented decision rather than a convenience (EntityQueryService.cs:158-164). LookupNameContract (EntityQueryService.cs:178) defaults to the same contract and gates GetAllForLookupAsync's nameProperty, which projects the named column verbatim for every row, unpaginated: an existence check against the entity was enough to dump a column the DTO never exposes (EntityQueryService.cs:447-458, rationale at EntityQueryService.cs:444-446 and EntityQueryService.cs:168-177). Two ADC services override them. SpeakerEntityQueryService narrows FieldContract to every SpeakerDTO field except the redacted Email and LinkedUserId (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/SpeakerEntityQueryService.cs:42-45, the override at SpeakerEntityQueryService.cs:54) and pins LookupNameContract back to the full DTO contract (SpeakerEntityQueryService.cs:60), and UserListEntityQueryService overrides FieldContract with its own roster contract (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UserListEntityQueryService.cs:69); every other ADC read runs on the DTO-derived default.

GetAllAsync (EntityQueryService.cs:330, with a six-parameter convenience overload at EntityQueryService.cs:309) is the four-step orchestration. It first asks the metadata provider which includes are supported and decides, through CanProject (EntityQueryService.cs:717-720), whether the read will be projected (EntityQueryService.cs:344-346), because field validation depends on that answer; a QuerySpecification that asks for tracking disqualifies projection exactly as the asTracking flag does (EntityQueryService.cs:345-346). (1) Validate every parameter up front with Result.Combine over the fields, sort-column, sort-direction, and filter validators, so a bad fields fails before any database hit (EntityQueryService.cs:348-353), re-stamping each error with the operation and entity name (EntityQueryService.cs:356-362). ValidateFields (EntityQueryService.cs:691) checks every name against what shaping will actually reflect over, the DTO, resolved through the map, the field contract, and the DTO's own properties exactly as sort and filter keys are, so an entity-only name that would shape every row into an empty object is refused; on the non-projected path it also requires a writable entity property, because the pipeline narrows the entity with a MemberInit before mapping (EntityQueryService.cs:693-698, rationale at EntityQueryService.cs:675-690). (2) Build the query: pack everything into EntityQueryParameters (EntityQueryService.cs:373-386), with the specification's OrderBy as the DefaultOrdering (EntityQueryService.cs:375), and take the base query from ListBaseQuery (EntityQueryService.cs:388, method at EntityQueryService.cs:727): Repository.Table or TableNoTracking from the asTracking flag when there is no specification (EntityQueryService.cs:729-730), otherwise the repository's QueryFor view of it, so the specification's criteria, soft-delete scope, includes, and tracking all scope the base query and none of its shape is lost; its own Skip/Take is never applied, because the request pages the list and the total counts the filtered set before that page is taken (EntityQueryService.cs:367-372). When the caller asks for tracking and the specification does not, the request wins through TrackedView (EntityQueryService.cs:745, chosen at EntityQueryService.cs:732-736), a private nested QuerySpecification that copies the scope's criteria, include paths, and soft-delete scope and adds WithTracking() (EntityQueryService.cs:747-761); ordering and paging are not copied, since QueryFor applies neither and the default ordering is read from the original specification (EntityQueryService.cs:739-744). (3) Execute on one of two branches: a registered projector, no tracking request, and no cross-source includes routes to ExecuteProjectedAsync and the mapper is never involved (EntityQueryService.cs:393-403); otherwise ExecuteAsync runs and DTOMapper.MapToDTOs converts the materialized entities (EntityQueryService.cs:404-415). Field shaping deliberately does not disqualify projection, because shaping runs after materialization over whatever object the pipeline produced (EntityQueryService.cs:712-715). (4) Shape and wrap: shape only when a field subset was requested, otherwise return the typed DTOs as-is to avoid a per-row ExpandoObject allocation and boxing (EntityQueryService.cs:424-426); both forms serialize to the same camelCase JSON, which is why the return type is PagedCollectionResult<object> rather than a typed collection (PagedCollectionResult<T>, and the contract note at IEntityQueryService.cs:12-14). The PaginationMetadata comes from BuildPaginationMetadata (EntityQueryService.cs:422, method at EntityQueryService.cs:829), whose job is to describe what the pipeline actually did rather than what the caller asked for: an unpaginated call reports the true total with the page size floored to the rows actually returnable, Math.Min(total, MaxUnboundedResultLimit), on page 1 (EntityQueryService.cs:843-846), and a paginated call reports the page number and page size of the same PageWindow that PagingMath.Clamp hands the pipeline, at the same MaxUnboundedResultLimit ceiling (EntityQueryService.cs:853-858), so the metadata cannot drift from the page actually read; because the window keeps the clamped page size even when its Take is the 0 sentinel for an unreachable offset, the metadata never advertises PageSize = 0 for a valid request (EntityQueryService.cs:822-826).

The by-id path has a fast lane worth knowing. GetEntityByIdAsync (EntityQueryService.cs:482) validates the fields as a non-projected read, since it always materializes the entity (EntityQueryService.cs:492-494), then tries TryGetByIdFastPathAsync (EntityQueryService.cs:201), which issues a single keyed TOP 1 WHERE Id = @id through the repository's include overload (EntityQueryService.cs:217). TryGetFastPathIncludes (EntityQueryService.cs:243) decides eligibility: a field projection, a specification, or a non-default idField disqualifies the request (EntityQueryService.cs:253-258), and so do unsupported (cross-source) navigations, since only the pipeline's populator can batch-load those (EntityQueryService.cs:265-269, rationale at EntityQueryService.cs:237-241). Requested includes do not disqualify it: the repository's include overload applies the same Include calls and auto-applies AsSplitQuery for a child collection (EFReadRepository.cs:418-431, delegating the split decision to SpecificationEvaluator.cs:103), and disqualifying on includes left the fast path unreachable for every entity that declares a navigation, because the REST by-id action defaults includeFKs to true (EntityQueryService.cs:228-236). The string id is converted with a TypeConverter cached per identifier type (EntityQueryService.cs:283, cache at EntityQueryService.cs:185), and the read runs on the filtered TableNoTracking (EFReadRepository.cs:387), so soft-delete query filters still apply, unlike FindAsync (EntityQueryService.cs:196-198, and the same trap documented at EFReadRepository.cs:409-414). Anything else falls through to the pipeline with a synthetic Id EQUALS <value> filter (EntityQueryService.cs:516-519) and returns Error.NotFound when the page comes back empty (EntityQueryService.cs:532-539). That fallback, BuildQueryAsync (EntityQueryService.cs:773), starts from the same ListBaseQuery the list read does (EntityQueryService.cs:786), so a specification scopes both reads alike and a WithSoftDeleted() scope is not silently lost on the by-id read alone (EntityQueryService.cs:766-772). GetByIdAsync (EntityQueryService.cs:545) layers DTO mapping and the same shape-only-if-fields rule on top; GetAllForLookupAsync (EntityQueryService.cs:438) returns lightweight BaseLookup<TIdentifierType> id/name pairs for dropdowns; ExistsAsync (EntityQueryService.cs:575) delegates straight to the repository. The class is built for extension over modification ([Rubric §1, SOLID]): Repository (EntityQueryService.cs:91), DTOToEntityPropertyMap (EntityQueryService.cs:112), and every query method are virtual, so a module subclass such as SpeakerEntityQueryService (SpeakerEntityQueryService.cs:15) overrides one behavior (SpeakerEntityQueryService.cs:51) without reimplementing the engine.

Two keyset reads sit beside the offset-paged list. GetPageByCursorAsync (EntityQueryService.cs:589) validates the single sort column exactly as the list read does (EntityQueryService.cs:596), swaps a mapped DTO name for its entity column (EntityQueryService.cs:608-613), and hands the KeysetPageRequest to the repository's own GetPageByCursorAsync, mapping the rows into a KeysetCollectionResult<T> (EntityQueryService.cs:615-619). GetChangesSinceAsync (EntityQueryService.cs:630) is the change feed built on that read, and its scope is one object, ChangeFeedSpecification<TEntity, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/ChangeFeedSpecification.cs:15), an internal sealed QuerySpecification constrained to AuditableBaseEntity<TIdentifierType> (ChangeFeedSpecification.cs:16). Its constructor builds the criteria and calls WithSoftDeleted() (ChangeFeedSpecification.cs:27-31), so a deleted row stays visible to be reported as a tombstone while every other global filter, the tenant filter included, stays in force (ChangeFeedSpecification.cs:8-12). BuildCriteria (ChangeFeedSpecification.cs:36) turns the optional lower bound into an inclusive LastModifiedOn >= since InlineSpecification (ChangeFeedSpecification.cs:39-42), wraps the caller's scope by its Criteria alone so a scope that is itself a shaped QuerySpecification is accepted (ChangeFeedSpecification.cs:44-46, rationale at ChangeFeedSpecification.cs:23-26), and ANDs whichever halves exist through AndSpecification, falling back to an always-true predicate when neither does (ChangeFeedSpecification.cs:48-54). The service normalizes the bound first, converting a local value to UTC and taking an unspecified one as UTC (ToUtc at EntityQueryService.cs:667-673), runs one keyset read ordered by LastModifiedOn ascending with Id as tie-break (EntityQueryService.cs:637-644, EntityQueryService.cs:624), maps only the live rows (EntityQueryService.cs:651), and emits one EntityChange<TEntityDTO, TIdentifierType> per row: a soft-deleted row becomes a tombstone with no Item, so none of its fields leave the service, and ChangedOn is LastModifiedOn, else CreatedOn (EntityQueryService.cs:653-661, rationale at EntityQueryService.cs:623-628). Both are ordinary members of IEntityQueryService with no default body (IEntityQueryService.cs:159, IEntityQueryService.cs:186), so every implementation provides them; the keyset read takes a specification only, with no includes, field projection, or filter dictionary (IEntityQueryService.cs:158). The feed reaches HTTP through an opt-in GET changes action on EntityControllerBase, present only on a controller carrying SupportsChangeFeedAttribute, which clamps the page size to MaxPageSize and passes its GetReadSpecificationAsync scope through (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:469-490). The client contract is written on the interface: page with the same since until the next cursor is null, then keep the largest ChangedOn as the next since; the bound is inclusive, so boundary rows come again and are applied idempotently, and a row that left the scope without being deleted yields no tombstone (IEntityQueryService.cs:180-185). This is [Rubric §9, API & Contract Design]: an incremental-sync contract every entity inherits without a bespoke endpoint.

End to end, one list request

The request reaches a read controller, EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> (Group 12), which resolves MaxPageSize per request from ApplicationSettings, falling back to 500 when unset (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:55-60), clamps the requested page size to it (EntityControllerBase.cs:168), binds ?filter= through QueryFilterModelBinder (EntityControllerBase.cs:165), and asks its own GetReadSpecificationAsync hook for a server-authored authorization scope (EntityControllerBase.cs:170). It calls IEntityQueryService.GetAllAsync (EntityControllerBase.cs:172). The service classifies the requested includes, validates fields, sort, and filters (an early failure short-circuits to an error result), and packages an EntityQueryParameters. EntityQueryPipeline then takes the projection path when a projector is registered and the read qualifies, or one of the two entity paths otherwise, starting from the base query the specification scoped through the repository, applying the dynamic filters as translated, parameterized WHERE clauses, sorting by the request's column or else the specification's default ordering, with the key tie-break when paginating, counting, paging through PagingMath, projecting the requested columns, materializing, and batch-loading any cross-source navigations. The service maps to DTOs (or skips mapping entirely on the projected path), shapes only if a field subset was asked for, and returns a Result<PagedCollectionResult<object>> that the controller unwraps into the HTTP body plus an X-Pagination header carrying the serialized metadata (EntityControllerBase.cs:187). One pipeline, every entity, validated input, server-side execution, and a clean extension point for navigations that cross a service boundary ([Rubric §6, CQRS & Event-Driven] on the read side, [Rubric §9, API & Contract Design] for the uniform query contract).

Query tags, naming the use case behind a statement

Two types in the Services/Query folder serve the operator reading a query store rather than the read path itself. QueryTagScope (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryTagScope.cs:20) is a static holder over an AsyncLocal<string?> (QueryTagScope.cs:22). Begin(handlerName) publishes the name of the CQRS use case the current flow is executing and returns a handle that restores the previous value on dispose, so a nested scope (an internal command executed inside another handler) unwinds correctly (QueryTagScope.cs:40-53); a null, empty, or whitespace name leaves the ambient value untouched, so no call site needs a guard (QueryTagScope.cs:44-47); and Current reads the innermost open scope, or null when none is open, which is the normal state for a background service, a seeder, or a directly constructed repository in a test (QueryTagScope.cs:28). The handle is the private AmbientScope (QueryTagScope.cs:61), a one-line IDisposable that assigns the captured previous value back (QueryTagScope.cs:63). The outermost scope of a request, whose previous value is null, is served by a single shared static instance, so opening a scope on the hot path allocates nothing at all and only a genuinely nested scope pays for an object (QueryTagScope.cs:49-52, the shared handle at QueryTagScope.cs:59).

The two ends are the decorator pipeline and the EF repositories. The logging decorators open the scope around each handler (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/LoggingQueryDecorator.cs:30 and LoggingCommandDecorator.cs:32), and QueryTags composes the ambient name with the query builder's own detail into the string the repository passes to EF Core's TagWith (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/QueryTags.cs:42, used on the specification path at SpecificationEvaluator.cs:38 and the include path at EFReadRepository.cs:537), turning an anonymous statement in a DBA's query store into a SQL comment naming the handler and the specification that asked for it. The value flows with the ExecutionContext, which is what lets a repository several awaits below the decorator read it without every signature in between growing a parameter, and nothing branches on it: a missing scope costs a less specific comment, never a behavior change (QueryTagScope.cs:6-18). It lives in the Application layer rather than Infrastructure because both ends need it and Application is the highest layer Infrastructure is allowed to see (QueryTagScope.cs:15-17). This is [Rubric §13, Observability & Operability] bought for one AsyncLocal and one using.

Also filed here: best-effort dispatch, domain event dispatch, and the upcaster registry

Five types in this group are not part of the read path at all; they are co-located in MMCA.Common.Application/Services and are grouped by that folder. BestEffort (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Resilience/BestEffort.cs:25) runs a side effect that must never fail its caller (cache eviction after a committed command, a fire-and-forget notification, an eviction broadcast onto the bus): ExecuteAsync awaits the action and turns any non-cancellation failure into exactly one Warning plus one metric increment instead of an exception that would roll back or 500 an operation whose real work already succeeded (BestEffort.cs:45, the swallow at BestEffort.cs:66-73). Cancellation is explicitly not swallowed: when the caller's own token is the reason the action stopped, the OperationCanceledException is rethrown so a host shutdown unwinds promptly (BestEffort.cs:59-64, rationale at BestEffort.cs:11-17). The two companions carry the telemetry: BestEffortLog (BestEffort.cs:81) is the source-generated Warning message, kept separate so the public helper need not be partial (BestEffort.cs:77-80), and BestEffortMetrics (BestEffort.cs:101) owns the MMCA.Common.BestEffort meter and its besteffort.dispatch.failed counter, tagged by a low-cardinality operation name (BestEffort.cs:104-117). It is its own meter rather than a counter folded into the CQRS metrics so an operator can drop or keep it independently of the RED metrics (BestEffort.cs:94-99). Callers span the framework and both apps: the framework's own output-cache eviction (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionExtensions.cs:86) and ADC's live broadcasts and cache-eviction processors (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Caching/BookmarkCacheEvictionProcessor.cs:62, MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Infrastructure/Live/LiveChannelPublishProcessor.cs:133, MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/SessionQuestions/UseCases/Submit/SubmitQuestionHandler.cs:214). This is [Rubric §13, Observability & Operability] (a quietly broken side effect becomes a metric, not a line in a log nobody reads) and [Rubric §29, Resilience & Business Continuity] (a non-essential failure degrades instead of propagating).

DomainEventDispatcher (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/DomainEventDispatcher.cs:23) is the sealed default IDomainEventDispatcher, the in-process dispatcher for domain events. DispatchAsync (DomainEventDispatcher.cs:60) sends every event to each registered IDomainEventHandler<T> (DomainEventDispatcher.cs:69), and when the event is also an IIntegrationEvent it first runs it through the IEventUpcasterRegistry to its terminal successor and dispatches that to each IIntegrationEventHandler<T> (DomainEventDispatcher.cs:74-79). A retired contract, including an outbox row written before an upgrade, therefore reaches the handlers written against the newest type, while intra-module domain handlers keep receiving the original type and instance (ADR-090, DomainEventDispatcher.cs:15-21). The registry is resolved lazily with GetService rather than GetRequiredService, so a dispatcher built directly in a test or in a bare provider that never called AddApplication() simply does no upcasting (DomainEventDispatcher.cs:27-33). Handler invocation avoids per-call reflection: a compiled expression tree per (event type, handler interface) is cached together with the closed handler type, which keeps MakeGenericType off the per-dispatch path (DomainEventDispatcher.cs:49-57, the builder at DomainEventDispatcher.cs:136), and a null handler resolved from DI is logged as a Warning and skipped rather than thrown on (DomainEventDispatcher.cs:117-121).

The last co-located type is EventUpcasterRegistry (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/EventUpcasterRegistry.cs:30), the default IEventUpcasterRegistry, which belongs to the integration-event story rather than to querying. It indexes every registered IEventUpcaster by its source contract and rejects a duplicate source, a self-mapping upcaster, or a chain cycle at construction time, throwing an InvalidOperationException that names the offenders (EventUpcasterRegistry.cs:50-82, the cycle check at EventUpcasterRegistry.cs:148-154); it precomputes each chain's terminal type once, because the graph is static after DI is built (EventUpcasterRegistry.cs:133); and it preserves the event envelope across every hop by stamping MessageId and DateOccurred from the pre-hop instance onto the upcasted one through cached PropertyInfo handles (EventUpcasterRegistry.cs:36, EventUpcasterRegistry.cs:169), so consumer-side inbox deduplication stays keyed on the id the producer published.

DynamicQueryConfig

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/DynamicQueryConfig.cs:18 · Level 0 · class (internal, static)

  • What it is: a one-field static holder for the single ParsingConfig that every System.Linq.Dynamic.Core call in the read pipeline passes, with UseParameterizedNamesInDynamicQuery turned on.
  • Depends on: nothing first-party. System.Linq.Dynamic.Core (ParsingConfig), the string-expression query API taught in primer §3.
  • Concept introduced, why a dynamic-LINQ value must become a SQL parameter and not a literal. Dynamic LINQ defaults UseParameterizedNamesInDynamicQuery to false, which compiles each @0 argument into a ConstantExpression. EF Core inlines constants, so filters["Name"] = ("EQUALS", "Widget") emitted WHERE [Name] = 'Widget': a distinct SQL string per distinct filter value (DynamicQueryConfig.cs:8-16). Two costs follow from that, both stated in the doc comment: SQL Server allocates a plan-cache entry per value, and EF's compiled-query cache misses on every request because the expression tree differs each time. With the flag on, the value is reached through a member access on a closure object instead, so EF parameterizes it and one plan serves every value. [Rubric §12, Performance & Scalability] (assesses whether the hot path avoids repeated per-request work): this is a one-line configuration change that converts an unbounded plan-cache footprint into a single cached plan. [Rubric §14, Testability] (assesses whether an invariant has an executable guard): the doc comment names its own regression test, QueryParameterizationTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/QueryParameterizationTests.cs:26), which inspects the emitted SQL through ToQueryString() (QueryParameterizationTests.cs:37) because nothing else in the suite looks at SQL shape.
  • Walkthrough: the whole type is one field. internal static readonly ParsingConfig Parameterized = new() { UseParameterizedNamesInDynamicQuery = true } (DynamicQueryConfig.cs:21-24). The doc comment on the field (:20) explains why it is a single shared instance rather than a per-call new: building a config per call would reintroduce the parse cost the flag exists to avoid.
  • Why it's built this way: ParsingConfig is immutable in use and thread-safe to share, so one static instance is both the cheapest and the only way to guarantee that no call site accidentally runs with the default (constant-folding) config. Keeping it internal means no consumer can pass a different config into the built-in strategies.
  • Where it's used: passed as the first argument to every query.Where(...) in all five built-in strategy classes (for example NumericFilterStrategy.cs:42, StringFilterStrategy.cs:32, DateTimeFilterStrategy.cs:32) and to every ordering call in QueryFieldService.ApplySorting (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryFieldService.cs:182, :177, :182, which qualify it as Filtering.DynamicQueryConfig.Parameterized because that class sits in the parent namespace).
  • Caveats / not-in-source: internal, so a consumer writing a custom IFilterStrategy outside this assembly cannot pass this config and gets the Dynamic LINQ default (constant inlining) unless it builds its own ParsingConfig.

FilterValueParser

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/FilterValueParser.cs:10 · Level 0 · class (internal, static)

  • What it is: a small internal helper that splits the comma-separated value list carried by the IN filter operator into a typed list (skipping any entry that fails to parse, for a caller that applies without validating), plus the shared up-front check that decides whether a raw value is usable at all for a given operator, which refuses a list with any unparseable item.
  • Depends on: nothing first-party. BCL only (string.Split, StringSplitOptions, LINQ All).
  • Concept introduced, set membership in a URL filter, and the split between lenient application and strict validation. The dynamic-filter vocabulary is one operator string plus one value string per property (see IFilterStrategy), so an IN filter has to smuggle a set, and BETWEEN a pair of bounds, through a single string. This class is the one place that decodes that convention: value.Split(Separator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) (FilterValueParser.cs:26, :41, :84), so "1, 2 ,3" and "1,2,3" behave identically and empty slots vanish. [Rubric §9, API & Contract Design] (assesses whether query conventions are uniform and predictable): every strategy that supports IN or BETWEEN decodes the list the same way, so a client never has to learn a per-type list syntax. [Rubric §15, Best Practices & Code Quality] (assesses defensive, exception-free handling of untrusted input): the class summary (:3-8) states the two halves. Validation refuses a list with ANY unparseable item, exactly as it refuses a malformed BETWEEN range, so a validated list always parses whole; application (ParseList) still skips an unparseable item rather than throwing, for a caller that applies filters without validating them.
  • Walkthrough
    • Separator (:12): a static readonly char[] holding a single comma, hoisted to a field so the array is allocated once rather than per call.
    • ParseList<T>(string value, Func<string, T?> parse) (:19-33), constrained where T : struct. The caller supplies the per-item parse delegate, so the parser stays type-agnostic. A null/whitespace input returns an empty list (:23-24); each part is run through parse and added only when the nullable result has a value (if (parse(part) is { } parsed), :28-29).
    • ParseStringList(string value) (:36-42): the string overload, no per-item parse needed, just the split with the same options, returning [] for empty input (:38-39).
    • CanParse<T>(string op, string value, Func<string, T?> parse) (:55-67): the shared value-usability check every value-type strategy delegates its CanParseValue to. It encodes the shape all six value strategies share, verbatim from the switch at :60-66: presence checks (IS EMPTY, IS NOT EMPTY) ignore the value and always return true; IN delegates to EveryItemParses (:63); BETWEEN delegates to HasExactlyTwoBounds (:64); every other operator needs the single scalar to parse (parse(value) is not null, :65). It null-guards the delegate (:58).
    • EveryItemParses<T>(string value, Func<string, T?> parse) (:78-87) is the strict IN check: a null/whitespace value fails (:81-82), otherwise it splits with the same options as ParseList (:84) and requires at least one item and every item to parse (parts.Length > 0 && parts.All(...), :86). Its remarks (:72-77) explain why it does not go through ParseList: skipping the unparseable items let "1,abc" validate, and the strategy then silently narrowed the filter to the items that happened to parse, a set the caller never asked for. Empty entries ("1,,2") are separators, not items, and are still ignored.
    • HasExactlyTwoBounds<T>(string value, Func<string, T?> parse) (:98-107) is the strict BETWEEN check, and its remarks (:92-97) explain why it exists as a separate private method rather than reusing ParseList: it deliberately does not pass RemoveEmptyEntries, so it sees the raw segment count (:104) and requires exactly two segments that both parse (:106). Going through ParseList would drop unparseable and empty segments first, which would let "5,abc,10" and "5,,10" validate as a two-bound range, and the strategies would then apply the surviving pair as bounds the caller never asked for.
  • Why it's built this way: the Func<string, T?> shape lets each caller pass its own TryParse in a static lambda or a static method group, so no closure is allocated (see NumericFilterStrategy<TNumber>.Parse, NumericFilterStrategy.cs:80-81). Returning a List<T> rather than an array matters downstream: LINQ Dynamic binds it as the receiver of a Contains call. Putting CanParse here rather than in each strategy is what keeps the validation rule and the application rule from drifting apart, which is exactly the class of bug QueryFilterService documents at QueryFilterService.cs:308-312.
  • Where it's used: every value strategy that supports IN or BETWEEN routes through ParseList: DateTimeFilterStrategy (DateTimeFilterStrategy.cs:59, :66), GuidFilterStrategy (GuidFilterStrategy.cs:38), and NumericFilterStrategy<TNumber> (NumericFilterStrategy.cs:67, :74, serving int, long and decimal); StringFilterStrategy (StringFilterStrategy.cs:58) calls ParseStringList. CanParse backs the CanParseValue override on all four value strategy classes (BoolFilterStrategy.cs:21, DateTimeFilterStrategy.cs:26, GuidFilterStrategy.cs:22, NumericFilterStrategy.cs:35-36).
  • Caveats / not-in-source: internal, so code outside this assembly cannot reuse it (and the strategy table in QueryFilterService is fixed, so there is no public way to plug in an outside strategy anyway). There is no size cap on the parsed list in this class; the only bound on how many values an IN filter may carry comes from the request size. MaxFilters = 50 (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:34, mirrored by QueryFilterModelBinder at MMCA.Common/Source/Presentation/MMCA.Common.API/ModelBinders/QueryFilterModelBinder.cs:34) caps the number of filters, not the number of values inside one.

IFilterStrategy

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/IFilterStrategy.cs:8 · Level 0 · interface (internal)

  • What it is: the Strategy-pattern contract for dynamic query filtering. Each implementation handles one CLR property-type family (string, the numeric types, DateTime, bool, Guid, the Email value object, a strongly typed identifier) and turns an operator key plus a raw string value into a .Where() clause on an IQueryable<T>. It is internal: the summary (IFilterStrategy.cs:3-7) states that the strategy table in QueryFilterService is fixed, so only the framework's own strategies implement it.
  • Depends on: nothing first-party. System.Linq (BCL).
  • Concept introduced, the Strategy pattern behind a fixed table. [Rubric §2, Design Patterns] (assesses whether patterns are applied idiomatically to real problems): instead of one growing switch (propertyType) inside a single filtering class, every filterable type family gets its own strategy object and QueryFilterService holds a Type -> IFilterStrategy table. Adding a filterable type inside the framework means adding a class and one table entry, with no edit to the existing strategies ([Rubric §1, SOLID], Open/Closed). [Rubric §9, API & Contract Design] (assesses consistent query conventions across the API surface): a single operator vocabulary for every entity in both apps flows from this one contract.
  • Walkthrough
    • IQueryable<T> Apply<T>(IQueryable<T> query, string property, string op, string value) (IFilterStrategy.cs:19). property is the entity property name or dotted path, op is the operator string already uppercased by the caller (stated in the doc comment, :16), and value is the raw string. The documented return contract (:18) is to hand back the original query when the operator is unrecognized: application is best-effort and never throws.
    • IReadOnlySet<string> SupportedOperators { get; } (:25), a required, non-nullable member. Every strategy declares its operator set (the built-in ones as a FrozenSet), and the doc comment (:21-24) names QueryFilterService.ValidateFilters as the check that runs before the strategy is applied, so an unknown operator is rejected up front as a validation failure instead of degrading into a silent no-op. There is no "skip validation" value: the service tests membership directly (QueryFilterService.cs:323, :480).
    • bool CanParseValue(string op, string value) => true (:45), a default interface member (a body supplied on the interface itself, so an implementer may omit it) and the fix for the failure mode the remarks spell out (:33-44). Because Apply fails open (an unparseable value yields the query unfiltered), an unvalidated ?filter=id:equals:abc would return the whole result set instead of no matches. Validating the value before execution turns that into a 400. [Rubric §11, Security] (assesses whether malformed input can widen a response beyond what the caller is entitled to see): a filter that silently disappears is not a neutral no-op, it is a broadened read. The default of true is documented (:41-42) as correct only for a strategy whose Apply never parses the value into another type (the e-mail strategy compares the raw text); every parsing strategy overrides it.
  • Why it's built this way: operators are plain strings rather than an enum, so the vocabulary can grow without a contract change; splitting per type keeps each type's parsing and comparison rules isolated and unit-testable. Keeping the interface internal and SupportedOperators required means every strategy that can reach a query also takes part in operator validation.
  • Where it's used: implemented by the five built-in strategy classes below, by EmailFilterStrategy, and by StronglyTypedIdFilterStrategy<TSelf, TValue>; the table, the dispatch (ResolveStrategy, QueryFilterService.cs:438), and the up-front validation (:304-305 for the two validation hooks) all live in QueryFilterService.

The five built-in filter strategy classes that follow share one shape: each is an internal sealed class implementing IFilterStrategy for one CLR type family (the generic NumericFilterStrategy<TNumber> is closed once per numeric type, so five classes serve seven value types), declaring its SupportedOperators as a HashSet built with StringComparer.Ordinal and frozen with .ToFrozenSet(StringComparer.Ordinal) (a FrozenSet is the read-optimised immutable set the framework reaches for whenever a lookup table is built once and read many times), then switching on the operator to build a LINQ Dynamic .Where() string. Five rules hold across all five and are not repeated in every section below.

  1. Bound parameters, never string concatenation, and never inlined constants. Values are passed as the positional parameter @0 (@0/@1 for BETWEEN) rather than interpolated into the expression text, and every call passes DynamicQueryConfig.Parameterized so the argument reaches EF Core as a real SQL parameter instead of a folded constant. That is both the injection-resistance property ([Rubric §11, Security]) and the plan-reuse property ([Rubric §12, Performance & Scalability]).
  2. Parse failure is a no-op at apply time. A value that fails to parse (or an unrecognized operator via the _ => default arm) returns the unfiltered query rather than throwing, exactly the no-op the IFilterStrategy contract promises.
  3. Validation closes the fail-open hole that rule 2 leaves. Because an unfiltered query is a widened response, the four value strategy classes override CanParseValue by delegating to FilterValueParser.CanParse with their own parse function, so QueryFilterService rejects the request before it executes. StringFilterStrategy overrides it more narrowly: every raw string is a valid string, so only an IN list with no usable item is refused.
  4. IN is set membership. The strategies that support IN decode a comma list through FilterValueParser and emit @0.Contains({property}), with the parsed list as the receiver @0 and the entity property as the argument, the shape LINQ Dynamic turns into SQL IN (...). An empty parsed list short-circuits to the unfiltered query at apply time. [Rubric §12, Performance & Scalability]: a UI that fetches many rows by id issues one query instead of a chain of round trips.
  5. BETWEEN is an inclusive range, IS EMPTY / IS NOT EMPTY are value-free null checks. BETWEEN reads exactly two comma-separated bounds and emits {property} >= @0 && {property} <= @1 (inclusive on both ends); a list that is not exactly two bounds is a no-op at apply time and a Filter.Value.Invalid error at validation time. IS EMPTY / IS NOT EMPTY take no value at all and emit {property} == null / {property} != null (a == null || .Length == 0 length test for the string strategy), so a nullable column can be filtered for presence.

The complete operator matrix, verbatim from source:

Strategy File:Line Supported operators
BoolFilterStrategy MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/BoolFilterStrategy.cs:12 IS, IS EMPTY, IS NOT EMPTY
DateTimeFilterStrategy MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/DateTimeFilterStrategy.cs:13 IS, IS NOT, IS AFTER, IS ON OR AFTER, IS BEFORE, IS ON OR BEFORE, IS EMPTY, IS NOT EMPTY, IN, BETWEEN
GuidFilterStrategy MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/GuidFilterStrategy.cs:13 EQUALS, NOT EQUALS, IN, IS EMPTY, IS NOT EMPTY
NumericFilterStrategy<TNumber> (int, long, decimal) MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/NumericFilterStrategy.cs:23 EQUALS, NOT EQUALS, GREATER THAN, LESS THAN, GREATER THAN OR EQUAL, LESS THAN OR EQUAL, IN, BETWEEN, IS EMPTY, IS NOT EMPTY
StringFilterStrategy MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/StringFilterStrategy.cs:12 CONTAINS, NOT CONTAINS, EQUALS, NOT EQUALS, STARTS WITH, ENDS WITH, IS EMPTY, IS NOT EMPTY, IN

Needle

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering.ValueObjects · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/ValueObjects/EmailFilterStrategy.cs:139 · Level 0 · record (private, sealed, nested in EmailFilterStrategy)

  • What it is: a one-property carrier, Needle(string Value) (EmailFilterStrategy.cs:139), declared as a private sealed record inside EmailFilterStrategy. Its only job is to hold the folded filter value so the expression tree can read it through a member access.
  • Depends on: nothing; it is a plain positional record.
  • Concept introduced, a captured value so EF Core parameterizes the needle. The doc comment (:134-138) states the purpose: EF Core turns a member access on a captured object into a query parameter instead of inlining a literal. BuildComparison wraps the folded value as Expression.Property(Expression.Constant(new Needle(...)), nameof(Needle.Value)) (:104), the hand-built-expression equivalent of the bound @0 parameter that the string-based strategies get from DynamicQueryConfig.Parameterized. [Rubric §11, Security]: the filter value never becomes SQL text.
  • Why it's built this way: a bare Expression.Constant(string) would be inlined as a literal, losing both parameterization and plan reuse; routing it through a record property forces the member-access shape.
  • Where it's used: only inside EmailFilterStrategy.BuildComparison (EmailFilterStrategy.cs:104); no usage outside the defining file.
  • Caveats / not-in-source: private, so no test addresses it directly; it is exercised through the Email filter tests.

TypeAndNameIgnoreCaseComparer

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:386 · Level 0 · class (private, sealed, nested in QueryFilterService)

  • What it is: the equality comparer for the (Type EntityType, string PropertyName) keys of the PropertyCache inside QueryFilterService. Two keys are equal when the entity type is the same and the property names match ignoring case (QueryFilterService.cs:390-392).
  • Depends on: nothing first-party. IEqualityComparer<T>, StringComparison.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase, HashCode (BCL).
  • Concept introduced, a cache key that matches the lookup it memoizes. LookupProperty resolves a filter key with BindingFlags.IgnoreCase (QueryFilterService.cs:373), so name, Name and NAME all reach one PropertyInfo. A cache keyed by the probed spelling would let each of the 2^N casings of an N-letter name mint its own never-evicted entry, which is the growth the PropertyCache remarks describe (:51-55, the SEC-Store-14 fix also carried by the lookup-selector cache in EFReadRepository). This comparer makes the dictionary compare names the way reflection does, and LookupProperty stores the property's canonical resolved.Name (:377), so every client casing of a real property lands on one entry. [Rubric §11, Security] (assesses whether a caller can grow server state at will) and [Rubric §12, Performance & Scalability].
  • Walkthrough
    • Instance (:388): a single shared instance, passed to the PropertyCache constructor (:57-58).
    • Equals (:390-392): reference equality on the Type, then string.Equals with StringComparison.OrdinalIgnoreCase on the name.
    • GetHashCode (:394-395): HashCode.Combine of the type and StringComparer.OrdinalIgnoreCase.GetHashCode(name), so two casings that compare equal also hash equal, the invariant a hashed collection needs.
  • Why it's built this way: canonicalizing the key bounds the cache to the real properties of the filtered entity types; the separate MaxPropertyCacheEntries cap of 512 (:42) bounds what remains, and a hit past the cap is resolved by reflection per request rather than admitted (:37-40).
  • Where it's used: only as the comparer of PropertyCache in QueryFilterService (:57-58); it has no usage outside the defining file.
  • Caveats / not-in-source: ordinal case-folding, not culture-aware; it compares exactly as the BindingFlags.IgnoreCase lookup is expected to resolve, and whether those two agree for every non-ASCII identifier is not determinable from source.

BoolFilterStrategy

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/BoolFilterStrategy.cs:12 · Level 1 · class (internal, sealed)

  • What it is: the IFilterStrategy for bool and bool? properties, and the smallest member of the family: one equality operator plus the two null checks.
  • Depends on: IFilterStrategy, FilterValueParser, DynamicQueryConfig; System.Collections.Frozen, System.Linq.Dynamic.Core (the query.Where(config, "expr", args) string-expression API taught in primer §3).
  • Walkthrough: SupportedOperators is the three-entry frozen set { "IS", "IS EMPTY", "IS NOT EMPTY" } (:14-17). CanParseValue (:20-21) delegates to FilterValueParser.CanParse with a static lambda over bool.TryParse. Apply<T> (:23-31) puts the value-free presence checks first, before the parse, because they do not depend on the value (the inline comment states this, :26): "IS EMPTY" => query.Where(DynamicQueryConfig.Parameterized, $"{property} == null") and the != twin (:27-28). The one equality arm parses inside a when guard, "IS" when bool.TryParse(value, out var boolValue) => query.Where(DynamicQueryConfig.Parameterized, $"{property} == @0", boolValue) (:29), so an unparseable value falls to _ => query (:30) rather than throwing, and is caught earlier by CanParseValue at validation time.
  • Why it's built this way: IS (rather than EQUALS) reads naturally for a boolean in a URL filter, and a boolean has no ordering, so no comparison operators exist to support; the null checks are the meaningful extra for a bool? column.
  • Where it's used: registered against both typeof(bool) and typeof(bool?) in QueryFilterService (QueryFilterService.cs:65-66). Note that the two keys get two separate instances, not one shared instance. Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Filtering/BoolFilterStrategyTests.cs.
  • Caveats / not-in-source: there is no IN arm, since a boolean set is degenerate.

DateTimeFilterStrategy

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/DateTimeFilterStrategy.cs:13 · Level 1 · class (internal, sealed)

  • What it is: the IFilterStrategy for DateTime and DateTime?, covering the six temporal comparisons, the two null checks, set membership (IN), and an inclusive BETWEEN range.
  • Depends on: IFilterStrategy, FilterValueParser, DynamicQueryConfig; System.Globalization, System.Collections.Frozen, System.Linq.Dynamic.Core.
  • Concept introduced, culture-invariant and zone-invariant parsing of untrusted input. FormatProvider is a static CultureInfo.InvariantCulture (:15), so "2026-07-21" parses identically regardless of the server's locale. That is the single-locale, culture-safe posture described in primer §4. The second half is the time zone: ParseDateTime (:80-81) passes DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, so an offset or Z in the value is honoured and normalized to UTC, a bare value is taken as UTC, and the result is always a DateTimeKind.Utc instant. Its doc comment (:72-79) states the reason: that is how the framework stores every DateTime, and the host's local zone never enters the result, so the same filter selects the same rows on every server in the cluster.
  • Walkthrough: SupportedOperators (:17-22) is the ten-entry frozen set. CanParseValue (:25-26) delegates to FilterValueParser.CanParse with the ParseDateTime method group. Apply<T> (:28-47) parses inside each temporal arm via a when clause over the same helper, for example "IS AFTER" when ParseDateTime(value) is { } dt => query.Where(DynamicQueryConfig.Parameterized, $"{property} > @0", dt) (:35-36). A failed parse yields null, the property pattern does not match, and the arm is skipped. The two null operators need no value (:43-44). The _ => arm routes to ApplyInOrRange (:46), which dispatches IN to ApplyIn and BETWEEN to ApplyBetween (:49-55). ApplyIn (:57-61) parses through FilterValueParser.ParseList with ParseDateTime (:59) and emits @0.Contains({property}) (:60); ApplyBetween (:63-70) requires exactly two bounds (:67) and emits {property} >= @0 && {property} <= @1 (:68). ParseDateTime (:80-81, internal static) is therefore the single parse path for validation, the scalar arms, IN and BETWEEN.
  • Why it's built this way: parsing per arm keeps the value-taking and the value-free operators in one switch without a pre-parse that would reject IS EMPTY for having no parsable value; routing every arm through one helper means validation and application cannot disagree on the parse styles; splitting IN/BETWEEN into a helper keeps the main switch under the analyzers' cyclomatic-complexity ceiling (the inline comment at :45 records the reason).
  • Where it's used: registered against typeof(DateTime) and typeof(DateTime?) in QueryFilterService (QueryFilterService.cs:71-72), as two instances. Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Filtering/DateTimeFilterStrategyTests.cs.
  • Caveats / not-in-source: a bare value is read as UTC, not as the caller's local time, so a client filtering on a local wall-clock time must send an explicit offset. Whether a given column actually holds UTC values depends on how the entity was written, which is not visible from this class.

GuidFilterStrategy

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/GuidFilterStrategy.cs:13 · Level 1 · class (internal, sealed)

  • What it is: the IFilterStrategy for Guid and Guid?, supporting equality, set membership (IN), and the two null checks.
  • Depends on: IFilterStrategy, FilterValueParser, DynamicQueryConfig; System.Collections.Frozen, System.Linq.Dynamic.Core.
  • Walkthrough: SupportedOperators (:15-18) is { EQUALS, NOT EQUALS, IN, IS EMPTY, IS NOT EMPTY }. CanParseValue (:21-22) delegates to FilterValueParser.CanParse with ParseGuid. Apply<T> (:24-34) parses the two single-value equality arms with a Guid.TryParse when guard (:27-28), handles the value-free null checks (:29-30), and routes IN last (:32) because a comma-separated list would never parse as one GUID (the inline comment at :31 records this). ApplyIn (:36-40) parses through FilterValueParser.ParseList with the ParseGuid method group (:38) and emits the receiver-inverted @0.Contains({property}) (:39). ParseGuid (:42) is the shared TryParse wrapper.
  • Why it's built this way: GUIDs have no meaningful ordering, so no comparison or range operators are provided; equality, membership, and presence are the full useful set for an opaque identifier.
  • Where it's used: registered against typeof(Guid) and typeof(Guid?) in QueryFilterService (QueryFilterService.cs:75-76). It is the strategy that serves by-id filtering wherever an entity's identifier alias resolves to Guid, and it is what the class doc comment on QueryFilterService points at when it says "Category.Id" now filters as a Guid rather than as a string (QueryFilterService.cs:18-20).
  • Caveats / not-in-source: no ordering operators and no BETWEEN, since a GUID range is meaningless.

NumericFilterStrategy<TNumber>

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/NumericFilterStrategy.cs:23 · Level 1 · class (internal, sealed, generic)

  • What it is: the one IFilterStrategy for every numeric column: int, long and decimal, each with its nullable twin (class summary, NumericFilterStrategy.cs:8-13). It supports the widest operator surface in the family: equality, the four ordering comparisons, set membership (IN), an inclusive BETWEEN, and the two null checks.
  • Depends on: IFilterStrategy, FilterValueParser, DynamicQueryConfig; System.Numerics (INumber<TSelf>), System.Globalization, System.Collections.Frozen, System.Linq.Dynamic.Core.
  • Concept introduced, one generic strategy over generic math. The constraint where TNumber : struct, INumber<TNumber> (:24) lets a single class parse and compare any of the three numeric types through the static abstract members .NET's generic math interfaces carry, so the operator switch exists once rather than once per numeric type; the summary states the payoff directly: "a new operator is written once" (:12). [Rubric §15, Best Practices & Code Quality] (assesses duplication and maintainability): three structurally identical classes collapse into one, and the three numeric types cannot drift apart in what they accept.
  • Walkthrough
    • SupportedOperators (:27-32): the ten operators, frozen with StringComparer.Ordinal.
    • CanParseValue (:35-36): delegates to FilterValueParser.CanParse with the private Parse helper.
    • Apply<T> (:39-52): the six single-value comparison arms (:42-47) each parse through the private TryParse helper inside a when guard and bind the value as @0; the two value-free null checks follow (:48-49); the _ => arm (:51, with the comment at :50 explaining that IN and BETWEEN parse a list rather than a scalar) routes to ApplyInOrRange (:57-63), whose own _ => query default is the no-op for an unknown operator.
    • TryParse (:54-55): TNumber.TryParse(value, CultureInfo.InvariantCulture, out result), the IParsable<TSelf> overload. The class remarks (:14-20) record why no explicit NumberStyles is passed: each type keeps its own default style (NumberStyles.Integer for int and long, NumberStyles.Number for decimal), and the invariant culture fixes . as the decimal separator, so the filter DSL means the same thing under every request culture.
    • ApplyIn (:65-69) parses through FilterValueParser.ParseList (:67) and emits the receiver-inverted @0.Contains({property}) (:68), short-circuiting an empty list to the unfiltered query.
    • ApplyBetween (:71-78) requires exactly two bounds (bounds.Count == 2, :75) and emits {property} >= @0 && {property} <= @1 (:76), inclusive on both ends (comment, :73).
    • Parse (:80-81): the TNumber? wrapper ParseList and CanParse take.
  • Why it's built this way: int is the default identifier alias across most modules and decimal (not double) is the money and quantity type, so these columns carry most by-id, by-parent-id and range filtering; giving all three the identical comparison/IN/BETWEEN surface means a client never has to know the underlying width or precision.
  • Where it's used: closed per type in the built-in table of QueryFilterService: NumericFilterStrategy<int> for int and int? (QueryFilterService.cs:67-68), NumericFilterStrategy<long> for long and long? (:69-70), and NumericFilterStrategy<decimal> for decimal and decimal? (:73-74). Reached indirectly by EntityQueryService's synthetic Id EQUALS filter (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:516-519) whenever the identifier alias is numeric and the by-id fast path did not apply. The IntFilterStrategyTests, LongFilterStrategyTests and DecimalFilterStrategyTests suites remain under MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Filtering/; none of them names NumericFilterStrategy< directly, so how they reach this class is not determinable from the file list alone.
  • Caveats / not-in-source: the nullable registrations reuse the non-nullable closed type (QueryFilterService.cs:68, :70, :74: NumericFilterStrategy<int> serves int?), so the bound parameter is the non-nullable TNumber even when the column is nullable; whether every provider translates that comparison identically is not determinable from source.

StringFilterStrategy

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/StringFilterStrategy.cs:12 · Level 1 · class (internal, sealed)

  • What it is: the IFilterStrategy for string properties, flat or at the leaf of a dotted path. It is the widest operator surface after the four ten-operator numeric and date strategies, and the only one whose operators are text predicates rather than comparisons.
  • Depends on: IFilterStrategy, FilterValueParser, DynamicQueryConfig; System.Collections.Frozen, System.Linq.Dynamic.Core.
  • Concept introduced, method-call expressions in LINQ Dynamic. Where the value strategies emit operator comparisons, the text operators emit method calls on the property: {property}.Contains(@0), !{property}.Contains(@0), {property}.StartsWith(@0), {property}.EndsWith(@0) (:32-37), and length tests for the presence checks: ({property} == null || {property}.Length == 0) and ({property} != null && {property}.Length > 0) (:50-51). LINQ Dynamic parses the string into an expression tree, and EF Core then translates those calls into LIKE predicates, so the match still runs in the database. [Rubric §12, Performance & Scalability]: CONTAINS translates to a leading-wildcard LIKE, which cannot use a normal B-tree index, that is a known cost of the convenience, not a defect of this class.
  • Concept introduced, why "empty" is a length test, not string.IsNullOrEmpty. The comment above ApplyPresenceOrSet (:43-46) records the reason: SQL Server translates string.IsNullOrEmpty to LIKE N'', and under a non-supplementary-character collation (SQL_Latin1_General_CP1_CI_AS) an emoji-only value carries no sort weight, so it compares equal to N'' and would wrongly match IS EMPTY. LEN counts code units instead, so the .Length form is correct for such a value.
  • Walkthrough: SupportedOperators (:14-18) is the nine-entry frozen set. CanParseValue (:26-27) is overridden, but narrowly: it returns true for every operator except IN, and for IN it requires FilterValueParser.ParseStringList to yield at least one item. The remarks (:21-25) record why only IN has a value shape to reject: an IN list with no usable item would otherwise fail open and return the unfiltered set, where every value-typed strategy refuses the same input; every other string operator accepts any value, including the empty string for EQUALS. Unlike the six value strategies it does not delegate to FilterValueParser.CanParse, because a string has no scalar parse to fail. Apply<T> (:29-39) handles the six value-taking text operators, then delegates the rest to ApplyPresenceOrSet (:47-54); the inline comment (:41-42) records why, the split keeps each method under the cyclomatic-complexity ceiling the analyzers enforce as errors. ApplyPresenceOrSet covers IS EMPTY, IS NOT EMPTY, and routes IN to ApplyIn (:56-60), which uses FilterValueParser.ParseStringList (:58) and emits the same @0.Contains({property}) receiver-inverted form as the other IN strategies.
  • Why it's built this way: the class doc comment (:6-11) still describes this strategy as the one used "for nested property paths (e.g. Category.Name) regardless of the target type, since LINQ Dynamic evaluates the full path as a string expression." Trust the code, not that doc comment: it describes an arrangement the code no longer has. QueryFilterService.ResolveFilterValueType (QueryFilterService.cs:410-429) walks a dotted path to its leaf and returns the leaf's own type, and ResolveStrategy (QueryFilterService.cs:440-441) hands back this strategy only when that resolved type is typeof(string). A path whose leaf cannot be walked does not fall back here at all: it fails closed (ResolveFilterValueType returns null, and both callers reject or skip the filter, QueryFilterService.cs:281-289 and :129-130). So "Category.Id" on a Guid key gets GuidFilterStrategy's operator set, and "Category.Nonexistent" gets a 400 rather than this strategy's operator set.
  • Where it's used: registered against typeof(string) in QueryFilterService (QueryFilterService.cs:64), and held a second time as the dedicated StringStrategy field (QueryFilterService.cs:90) that ResolveStrategy returns for any resolved value type equal to typeof(string) (QueryFilterService.cs:440-441). Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Filtering/StringFilterStrategyTests.cs.
  • Caveats / not-in-source: nothing here escapes LIKE wildcards, so a % inside a CONTAINS value reaches the database as part of the pattern. The value is still a bound parameter (rule 1 of the family preamble), so this is a matching-semantics detail, not an injection vector.

StronglyTypedIdFilterStrategy<TSelf, TValue>

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/StronglyTypedIdFilterStrategy.cs:24 · Level 3 · class (internal, sealed)

  • What it is: the IFilterStrategy for a column typed as a strongly typed identifier (ADR-115) instead of its wrapped primitive: the client still sends the primitive (filters[Id].value=42), the strategy parses it into the wrapper, and the query compares wrapper to wrapper so EF Core's value converter turns both sides into the same primitive column (StronglyTypedIdFilterStrategy.cs:10-13).
  • Depends on: IFilterStrategy, FilterValueParser, DynamicQueryConfig; MMCA.Common.Shared.Identifiers (IStronglyTypedId<TSelf, TValue>, StronglyTypedId), System.Collections.Frozen, System.Globalization, System.Linq.Dynamic.Core.
  • Concept introduced, an equality-only operator surface because a record struct has no <. The class doc comment (:14-20) states the constraint: only EQUALS, NOT EQUALS, IN, IS EMPTY, and IS NOT EMPTY are supported, because a record struct declares ==/!= and nothing else, so there is no > to build a range predicate from and an ordering comparison on an opaque identifier is not something a caller should be asking for. An unsupported operator is refused by QueryFilterService.ValidateFilters as a 400 rather than silently widening the result set, the same fail-closed posture the built-in strategies share.
  • Walkthrough
    • SupportedOperators (:29-32) is the five-entry frozen set, matching the class doc's list.
    • CanParseValue (:35-36) delegates to FilterValueParser.CanParse with ParseIdentifier.
    • Apply<T> (:39-48) mirrors GuidFilterStrategy's shape: EQUALS and NOT EQUALS parse inside a when guard through the private TryParse (:42-43), the two null checks are value-free (:44-45), and IN routes to ApplyIn (:46).
    • TryParse (:50-51) wraps StronglyTypedId.TryParse<TSelf, TValue> with CultureInfo.InvariantCulture.
    • ApplyIn (:53-59) parses through FilterValueParser.ParseList with ParseIdentifier (:55) and emits the receiver-inverted @0.Contains({property}) (:58), the same form the other IN strategies use.
    • ParseIdentifier (:61-62) is the private wrapper both CanParseValue and ApplyIn pass to FilterValueParser.
  • Why it's built this way: the strategy is closed over a specific (TSelf, TValue) pair only at runtime, by the non-generic partner class also named StronglyTypedIdFilterStrategy (StronglyTypedIdFilterStrategy.cs:69-90): TryCreate calls StronglyTypedId.TryDescribe to recognize the property type, then builds the closed generic through Activator.CreateInstance(typeof(StronglyTypedIdFilterStrategy<,>).MakeGenericType(identifierType, valueType)) (:81-84). QueryFilterService.ResolveStrategy calls TryCreate only after its own Strategies table misses, and memoizes the result with Strategies.GetOrAdd (QueryFilterService.cs:446-448), so the reflection cost is paid once per identifier type, not once per request. That is what lets a consumer adopt services.AddStronglyTypedIds(...) without a startup RegisterStrategy call per identifier.
  • Where it's used: created on demand inside QueryFilterService.ResolveStrategy (QueryFilterService.cs:438-449) whenever a filter's resolved value type is a strongly typed identifier with no explicitly registered strategy. Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Filtering/StronglyTypedIdFilterStrategyTests.cs.
  • Caveats / not-in-source: internal, so it is reached only through QueryFilterService's reflection fallback, never registered explicitly by a consumer; no ordering or BETWEEN operators, the same rationale GuidFilterStrategy gives for an opaque identifier having no meaningful range.

EmailFilterStrategy

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering.ValueObjects · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/ValueObjects/EmailFilterStrategy.cs:27 · Level 5 · class (internal, sealed)

  • What it is: the IFilterStrategy for the Email value object (MMCA.Common.Shared.ValueObjects.Contact), so a grid's Email column filters on an entity that stores the value object rather than a string. It is registered against typeof(Email) in QueryFilterService (QueryFilterService.cs:77). The doc comment (:8-26) lists the eight operators.
  • Depends on: IFilterStrategy, Needle; System.Linq.Expressions, System.Reflection, System.Collections.Frozen.
  • Concept introduced, two translations of "the address text", chosen by query provider. The value object is mapped with a value converter onto one string column, and EF Core cannot translate member access into a converted value, so e.Email.Value.Contains(x) fails at query time (:13-17). Against a database the predicate reads the column through (string)(object)e.Email (:56-59, :220): EF Core strips the two casts and compares the stored string. LINQ to Objects cannot do that cast, so an in-memory query (query.Provider is EnumerableQuery, :56) reads Email.Value behind a null guard instead (:102-119). The choice is made on the provider, never on configuration. Unlike its siblings it builds an Expression tree by hand rather than a LINQ Dynamic string.
  • Walkthrough: SupportedOperators (:35-39) is the eight-entry frozen set (the string set without IN). Apply<T> (:42-71) returns the query unchanged for an unsupported operator (:44-47) or a path that does not resolve to an Email (:50-54), then switches on the operator (:61-68): NOT CONTAINS and NOT EQUALS wrap the positive comparison in Expression.Not, and IS NOT EMPTY negates BuildIsEmpty. BuildMemberAccess (:74-89) walks a dotted path case-insensitively and returns null unless the leaf type is Email (:88). BuildIsEmpty (:95-100) is IsNullOrEmpty(address) against a database and adds a null-Email check in memory. BuildComparison (:102-119) folds the value with ToStoredCase(value.Trim()) (:104), wraps it in a Needle, and emits Contains, StartsWith, EndsWith or equality. ToStoredCase (:125-132) lowers each character with char.ToLowerInvariant, the form Email.Create stores, so a match is case-insensitive on every database collation (:22-25).
  • Why it's built this way: a value-object column cannot go through the LINQ Dynamic string path the other strategies share, and a hand-built tree lets the strategy pick the translatable shape per provider while still parameterizing the needle ([Rubric §11, Security]). Folding to the stored case makes the match independent of the database collation.
  • Where it's used: seeded into the Strategies table at QueryFilterService.cs:77. Behaviour is pinned by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/EmailFilterTranslationTests.cs (database translation). ADR-034 mentions it.
  • Caveats / not-in-source: it does not override CanParseValue, since every raw string is a valid needle. It does not support IN. Like the string strategy, CONTAINS becomes a leading-wildcard LIKE.

QueryFilterService

MMCA.Common.Application · MMCA.Common.Application.Services.Filtering · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:25 · Level 6 · class (public, static)

  • What it is: the static strategy table plus dispatcher that applies and validates dynamic filters. It owns the fixed Type -> IFilterStrategy table, a memo of strategies built for strongly typed identifier columns, a PropertyInfo cache and the per-request filter cap, and it is the single point where a parsed URL filter meets an IQueryable.
  • Depends on: IFilterStrategy and the six built-in strategy classes (BoolFilterStrategy, DateTimeFilterStrategy, GuidFilterStrategy, NumericFilterStrategy<TNumber>, StringFilterStrategy, EmailFilterStrategy), the nested TypeAndNameIgnoreCaseComparer, StronglyTypedIdFilterStrategy<TSelf, TValue> (built on demand, ADR-115), QueryFieldContract, Result, Error; System.Reflection, System.Collections.Concurrent, System.Collections.Frozen.
  • Concept introduced, a fixed strategy table plus a validate-before-execute boundary. [Rubric §2, Design Patterns] (Strategy): BuiltInStrategies (QueryFilterService.cs:60-78) is a FrozenDictionary built once at type initialization with fourteen entries, one per supported CLR type including each nullable variant (string, bool/bool?, int/int?, long/long?, DateTime/DateTime?, decimal/decimal?, Guid/Guid?) plus the Email value object (:77, EmailFilterStrategy); the three numeric pairs share the generic NumericFilterStrategy<TNumber>, closed per type (:67-70, :73-74). There is no public registration method: the class doc comment (:15-16) states that the built-in table is fixed, and the only types resolved beyond it are strongly typed identifier columns, whose strategies are built on first use into the separate IdentifierStrategies ConcurrentDictionary (:80-84, ADR-115), keyed by the model's CLR types and never by client input. [Rubric §9, API & Contract Design] (assesses validation at the right boundary): ValidateFilters runs the count, property, path, type, operator, and value checks before the query is built, so a bad filter becomes a precise validation failure rather than a LINQ Dynamic parse exception at execution time or, worse, a silently widened result set.
  • Concept introduced, a per-request filter cap that refuses rather than truncates. MaxFilters (:34, a public const int of 50) bounds how many filters one request may carry. Its doc comment (:27-33) gives the two reasons: an unknown name is resolved by reflection rather than memoized (see PropertyCache below), so the cap bounds the reflection work a caller can demand, and a request over the cap is refused with Filter.TooMany (:192-198) before any key is resolved, because dropping the surplus would silently widen the result set past what the caller asked for. [Rubric §11, Security] and [Rubric §12, Performance & Scalability]. QueryFilterModelBinder re-exports the same constant (MMCA.Common/Source/Presentation/MMCA.Common.API/ModelBinders/QueryFilterModelBinder.cs:34) and keeps every complete entry, leaving the refusal to this class.
  • Concept introduced, resolving a nested filter path to its leaf, and failing closed when it will not resolve. The class doc comment states the rule (:18-22): a dotted path such as "Category.Name" is walked segment by segment, the leaf's type picks the strategy (so "Category.Id" filters as a Guid rather than as a string), and a path whose leaf cannot be reached is rejected by ValidateFilters as an unknown property. That second half is the fail-closed posture: ResolveFilterValueType returning null is treated as "the entity does not have this property", not as "guess at the string strategy". [Rubric §11, Security] (assesses whether malformed input can widen a response): guessing would have let a filter the query cannot express disappear, returning an unfiltered 200. [Rubric §9, API & Contract Design]: the alternative failure, letting Dynamic LINQ blow up at query-build time, turns a bad request into a 500.
  • Concept introduced, gating an unmapped filter key against the response contract rather than the entity (SEC-Common-25, SEC-ADC-09, SEC-Store-13). Each public entry point has exactly one overload, and it takes a QueryFieldContract? (ApplyFilters, :109-113; ValidateFilters, :181-184). Passing null is an explicit opt-out to entity-wide reflection, correct only for a caller whose filter keys are all server-authored, and the parameter doc (:103-107, :176-179) records that there is deliberately no overload omitting the argument, so the choice is always visible at the call. Every key is routed through IsAdmissibleKey (:224-234) before it reaches reflection: a server-mapped key is trusted for what it names but is still capped at QueryFieldContract.IsWithinNavigationDepth (:230), since every extra dotted segment past MaxNavigationDepth is another LEFT JOIN, the join-explosion load a self-referencing navigation repeated hundreds of times produces; a key the map did not author is client input and must both pass that depth check and be declared filterable by fieldContract.AllowsClientKey (:233), so a caller can neither walk the object graph nor address a column no DTO exposes. ApplyFilters drops a key that fails the gate (:131-132); ValidateFilters, through ValidateSingleFilter (:247-255), turns it into the same Filter.Property.NotFound error an unknown property gets, so the two paths agree on what a caller may reach. [Rubric §11, Security]: this closes a hole the entity-reflection path left open, an unmapped key could address any public entity property, including one the response DTO never carries.
  • Concept introduced, case-insensitive key resolution with a canonical member name. A filter key resolves against the entity case-insensitively: LookupProperty passes BindingFlags.IgnoreCase (:372-373, the comment naming the sort column, the field contract and the filter dictionary as the precedents). Resolving loosely is only half of it: the Dynamic LINQ expression must then name a member that actually exists, so ApplyFilters picks a memberPath (:148-155). A flat client key is applied under the property's declared name (propertyInfo.Name), so the emitted member access never depends on how the client cased it; a server-authored map entry, or any dotted path, is applied verbatim. The comment records why the server-authored case must not be substituted: an entry may be an expression rather than a member (ADC maps Speaker "FullName" to a FirstName + " " + LastName concatenation because the entity's own FullName is unmapped), and replacing it with the property name produces a query EF cannot translate.
  • Concept introduced, aliased keys and one operator vocabulary. Both ApplyFilters and ValidateFilters first reduce each dictionary key through QueryFilterKeys.PropertyOf(key) (:120-122, :203): an aliased key such as "Name~search" is a second filter on the same property, resolved as the bare key so it ANDs with that key's own filter. The operator then passes through NormalizeOperator (:146, :269, defined :461-470) once, ahead of both validation and application: it trims, upper-cases (so MudBlazor's lower-case "contains" and "is empty" match) and maps the comparison symbols a grid's number column sends (=/==, !=/<>, >, >=, <, <=) onto their word forms (EQUALS, NOT EQUALS, GREATER THAN, GREATER THAN OR EQUAL, LESS THAN, LESS THAN OR EQUAL), so every strategy accepts both spellings with identical meaning and no client translates (the doc comment at :455-457 names the numeric strategy's three types, int, long and decimal, as the beneficiaries).
  • Walkthrough
    • PropertyCache (:57-58): ConcurrentDictionary<(Type EntityType, string PropertyName), PropertyInfo> constructed with TypeAndNameIgnoreCaseComparer.Instance, so a reflected lookup is paid once per entity/property pair. Read the doc comment (:44-56) and LookupProperty<TEntity> (:367-380) together: only successful lookups are memoized (if (resolved is not null && PropertyCache.Count < MaxPropertyCacheEntries), :376-377). Caching misses too would let any caller grow a process-lifetime static dictionary without bound simply by filtering on names that do not exist, and because the request still gets a clean 400 the growth would be invisible in error metrics. A miss costs one reflection lookup, bounded per request by this class's own MaxFilters (:34, cited as the bound in the ResolvePropertyInfo doc comment at :350-351). This is an unbounded-memory-growth defense, [Rubric §11, Security] and [Rubric §12, Performance & Scalability]. A hit is stored under the property's canonical name (TryAdd((typeof(TEntity), resolved.Name), resolved), :377) and the comparer folds case, so every client casing of one property lands on one entry (the SEC-Store-14 fix, remarks :51-55). MaxPropertyCacheEntries (:42, 512) bounds what remains: past the cap a hit is resolved by reflection per request rather than admitted (:37-40), and the Count check, which takes every bucket lock, runs only on a cache miss (comment, :375).
    • BuiltInStrategies (:61-78) and IdentifierStrategies (:84): the frozen built-in table and the on-demand identifier memo described above, kept as two dictionaries so the client-independent built-ins are immutable after type initialization while only the model-bounded identifier entries are ever added at run time.
    • StringStrategy (:90): a dedicated StringFilterStrategy instance held apart from the table, returned by ResolveStrategy whenever the resolved value type is typeof(string) (its doc comment at :86-89 names both cases: a flat string property, or a nested path whose leaf is one).
    • ApplyFilters<TEntity> (:109-163): for each (key, (op, value)) it reduces the key to its bare property (:120-122) and translates the DTO name through dtoToEntityPropertyMap (:124-126), gates the resolved key through IsAdmissibleKey (:131-132), resolves the PropertyInfo through ResolvePropertyInfo (:134) and silently skips an unresolvable property (:136-137), then resolves the value type through ResolveFilterValueType and skips again when the path leaf cannot be reached (:142-144). The comment above that second skip (:139-141) is explicit about the reasoning: ValidateFilters rejects all of these cases, so reaching here means the caller never validated, and applying a filter the query cannot express is worse than dropping it. Only then does it normalize the operator once (:146 via NormalizeOperator, the caller-side half of the IFilterStrategy contract), choose the memberPath (:153-155), resolve the strategy from the value type (:157), and apply it under that member path when one exists (:158-159). It does not enforce MaxFilters: the cap is a validation-time refusal.
    • ValidateFilters<TEntity> (:181-208): returns success for a null/empty filter map (:188-189), refuses a map over MaxFilters as a whole with a single Filter.TooMany error before resolving any key (:191-198), otherwise runs ValidateSingleFilter per entry with fieldContract threaded through (:202-203) and collects all errors into one Result (:205-207), so a client sees every problem at once rather than one per round trip.
    • ValidateSingleFilter<TEntity> (:236-306) is a five-gate ladder, each gate returning early so one filter never yields two errors about the same mistake. Gate zero: IsAdmissibleKey fails, Filter.Property.NotFound naming the key as not filterable (:247-255). Gate one: reflection cannot resolve the property at all (:259), the same code, a different message. Gate two: the property resolves but the dotted path's leaf does not (:281-289), again Filter.Property.NotFound naming the path. Gate three: no strategy resolves for the value type (:293), Filter.Type.NotSupported. Gate four: it delegates to ValidateOperatorSupported for Filter.Operator.NotSupported (:480) and ValidateValueParseable for Filter.Value.Invalid (:304-305). Every error carries source: nameof(ValidateFilters) so the origin is identifiable in a problem-details payload.
    • ValidateValueParseable (:313-334) is the guard behind rule 3 of the family preamble: without it the strategy would return the query unfiltered, so a malformed value would widen the response to the full result set instead of narrowing it to no matches. It deliberately stays silent when the operator itself is already invalid (:321-324, a direct SupportedOperators.Contains test, since every strategy must declare its set), so one bad filter does not produce two errors describing the same mistake; otherwise it asks strategy.CanParseValue (:326), which for an IN list means every item must parse (see FilterValueParser).
    • ResolvePropertyInfo (:354-361): probes the DTO-facing name first, then the mapped entity name (its root segment for a dotted path, :356-358). The doc comment (:340-343) records why both the apply path and the validate path share it: were the two to fall back in a different order, a plain rename entry such as ["Name"] = "Title" could pass validation and then be silently dropped, returning an unfiltered result set with a 200.
    • ResolveFilterValueType<TEntity> (:410-429): for a flat property this is the property's own type (:412-413); for a dotted path it walks each segment to the leaf's type (:415-428), starting from the path's own root rather than from the already-resolved property (:417-419, because for a nested path the DTO-facing name and the path root need not agree). The walk stops the moment a segment is not a public instance property of the preceding segment's type (:421-426), and the remarks (:403-409) spell out that the null result is a fail-closed signal, not a fallback: validation rejects it as an unknown property and application skips it.
    • ResolveStrategy (:438-449): typeof(string) maps to StringStrategy (:440-441), a built-in type is a TryGetValue hit on BuiltInStrategies (:443-444); otherwise it asks StronglyTypedIdFilterStrategy.TryCreate to build a strategy for a strongly typed identifier column and, when that succeeds, memoizes it into IdentifierStrategies with GetOrAdd (:446-448), so a non-built-in, non-identifier type is the only case that yields null and fires gate three of the validation ladder.
  • Why it's built this way: validating up front converts would-be runtime exceptions and silently widened responses into precise validation errors at the API boundary; the property cache amortises resolution to first use per process while refusing to memoize client-controlled misses, keying every casing of a real property to one entry and capping the total, and the filter cap refuses rather than truncates so the reflection bound never costs a silently widened result; freezing the built-in table removes process-global mutable state from the request path; gating an unmapped key against the response contract closes the same class of over-exposure the property cache and the nested-path fail-closed rule already close, just at the key-name layer instead of the type layer; resolving case-insensitively but emitting the declared name keeps the key matching rule consistent with sorting and the field contract without letting client casing reach the expression; and resolving a nested path to its leaf type is what lets one operator vocabulary apply uniformly to flat and nested properties without the string strategy standing in for everything.
  • Where it's used: ValidateFilters is called from EntityQueryService.GetAllAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:352); ApplyFilters is called inside EntityQueryPipeline on both of its paths, before materialization (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:79 and :144). All three calls pass the caller's FieldContract to the single overload. The filter map itself is produced at the API edge by QueryFilterModelBinder. Its own behavior is pinned by five test classes under MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Filtering/ (QueryFilterServiceTests, QueryFilterServiceValidateTests, QueryFilterServiceGridOperatorTests, QueryFilterServicePropertyCacheTests, StronglyTypedIdFilterStrategyTests) plus MMCA.Common.Application.Tests/Services/Query/QueryFieldContractSecurityTests.cs and QueryFilterAliasedKeyTests.cs, on top of the seven per-strategy suites in the same folder. Downstream, ADC pins its public schedule's Room filter through the same two calls (MMCA.ADC/Tests/Modules/Conference/MMCA.ADC.Conference.Application.Tests/Sessions/SessionRoomFilterTests.cs:18), so a renamed or retyped Session.RoomId fails a test rather than silently dropping the filter.
  • Caveats / not-in-source: this is a static class, not a DI-resolved service, and its built-in table is frozen, so a host cannot add a filter type: a custom value object column is not filterable unless it is a strongly typed identifier (ADR-115), and there is no per-tenant table. Nullable variants are separate instances rather than a shared one (:64-77), which costs a few extra objects but keeps the table declaration flat. ResolveFilterValueType walks only public instance properties (BindingFlags.Public | BindingFlags.Instance), so a path through a non-public member is unreachable by design. The case-insensitive lookup covers the root segment only: the segment walk past it (:424) does not pass BindingFlags.IgnoreCase, so a dotted path needs every segment after the first cased as declared, and because a dotted path is applied verbatim (:153-154) its casing reaches the Dynamic LINQ expression unchanged. MaxFilters is enforced only by ValidateFilters; a caller that applies without validating gets no cap.

BestEffortLog

MMCA.Common.Application · MMCA.Common.Application.Services.Resilience · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Resilience/BestEffort.cs:81 · Level 0 · class (internal, static, partial)

  • What it is: the source-generated logging companion of BestEffort. One [LoggerMessage] method that emits the single Warning a swallowed side-effect failure produces.
  • Depends on: nothing first-party. Microsoft.Extensions.Logging (ILogger, the [LoggerMessage] source generator).
  • Concept introduced, source-generated logging. [Rubric §13, Observability & Operability] assesses whether diagnostic output is structured and cheap enough to leave on in production. ILogger.LogWarning("... {Operation} ...", operation, ex) boxes its arguments and parses the message template on every call; the [LoggerMessage] attribute instead makes the compiler emit a strongly-typed, allocation-free DispatchFailed method with the template pre-parsed and the event wired up once. The type has to be partial for the generator to add the body, which is exactly why it is a separate companion class: the doc comment (BestEffort.cs:77-80) records that the reason is to keep the public BestEffort helper from having to be partial itself.
  • Walkthrough: one member. [LoggerMessage(Level = LogLevel.Warning, Message = "Best-effort operation '{Operation}' failed and was swallowed; the caller's outcome is unaffected")] over internal static partial void DispatchFailed(ILogger logger, string operation, Exception exception) (BestEffort.cs:83-86). The Operation placeholder becomes a structured log property, so an operator can group failures by side effect without parsing the message string, and the Exception parameter is passed to the logger as the exception rather than concatenated into the text.
  • Why it's built this way: Warning, not Error, is the deliberate level. The caller's real work has already succeeded (that is the whole premise of a best-effort dispatch), so an Error would page someone for an outcome that is by definition not a failure of the operation. ADR-096 records the helper's contract that this log is half of.
  • Where it's used: called from the catch-all arm of BestEffort.ExecuteAsync (BestEffort.cs:72) and nowhere else.

BestEffortMetrics

MMCA.Common.Application · MMCA.Common.Application.Services.Resilience · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Resilience/BestEffort.cs:101 · Level 0 · class (internal, static)

  • What it is: the OpenTelemetry instrument behind BestEffort: a meter, one counter, and the one-line helper that increments it with the operation name as a tag.
  • Depends on: nothing first-party. System.Diagnostics.Metrics (Meter, Counter<long>).
  • Concept introduced, a metric as the durable signal for a swallowed failure. [Rubric §13, Observability & Operability] assesses whether a system's failure modes are visible in telemetry rather than only in logs. A swallowed exception is the classic invisible failure: nothing 500s, nothing retries, and the log line scrolls past. Counting each swallow on a counter turns "the cache eviction quietly stopped working three weeks ago" into a chart with a step change in it. The class doc (BestEffort.cs:94-99) explains why it is a meter of its own rather than a counter folded into the CQRS meter: best-effort dispatch is not part of the CQRS pipeline (handlers, hosted services and consumers all call it), so a separate meter lets an operator drop or keep it independently of the RED metrics.
  • Walkthrough
    • internal const string MeterName = "MMCA.Common.BestEffort" (BestEffort.cs:104) and private static readonly Meter Meter = new(MeterName) (BestEffort.cs:106): one process-wide meter, created once.
    • internal static readonly Counter<long> DispatchFailed (BestEffort.cs:109-112), the instrument besteffort.dispatch.failed with unit {operation} and a description naming exactly what it counts.
    • internal static void RecordFailure(string operation) => DispatchFailed.Add(1, new KeyValuePair<string, object?>("operation", operation)) (BestEffort.cs:116-117): one increment, one tag. The tag is why the BestEffort doc insists the operation name be a low-cardinality constant: a tag value per request would multiply the time series.
  • Why it's built this way: a host exports the counter by registering the meter name, and the Aspire service defaults do that already (AddMeter("MMCA.Common.BestEffort") at MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.Telemetry.cs:338). Note the meter name is duplicated there as a string literal rather than referenced, because the Aspire package has no reference to Application; the class doc (BestEffort.cs:92-93) records that duplication as deliberate.
  • Where it's used: only from BestEffort.ExecuteAsync's catch arm (BestEffort.cs:71). The tagging behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Resilience/BestEffortTests.cs:62, which asserts the counter records the failure with its operation tag.

PropertyAccessor

MMCA.Common.Application · MMCA.Common.Application.Services.Query (private, nested in QueryFieldService) · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryFieldService.cs:53 · Level 0 · record struct (readonly, private)

  • What it is: a tiny private readonly record struct declared inside QueryFieldService that bundles a property's CLR name, its pre-computed camelCase JSON name, and a compiled Func<object, object?> getter, so a property value can be read without per-call reflection.
  • Depends on: nothing first-party. System.Reflection, System.Linq.Expressions, System.Text.Json (JsonNamingPolicy) from the BCL.
  • Concept introduced, compile-once expression delegates instead of per-call reflection. [Rubric §12, Performance & Scalability] (assesses whether hot paths avoid avoidable per-request work): PropertyInfo.GetValue allocates an argument array on every invocation, and shaping a 1,000-row page with 20 properties would pay that cost 20,000 times. The getter is instead built as an expression tree and compiled once per property, inside the per-type loop in GetAccessors (QueryFieldService.cs:60-69): a parameter of object (:56), a cast to the entity type (:57), the property access (:58), a box back to object (:59), then Expression.Lambda<Func<object, object?>>(...).Compile() (:60). Caching the result collapses each later read to a delegate call. The readonly record struct shape is the idiomatic .NET carrier for a small immutable tuple of values: no heap allocation per element, structural equality for free.
  • Walkthrough: the whole type is one positional declaration, private readonly record struct PropertyAccessor(string PropertyName, string CamelCaseName, Func<object, object?> GetValue) (QueryFieldService.cs:53).
    • PropertyName is the raw CLR name (:61) and is what a requested fields= entry is matched against, case-insensitively, when the accessor array is filtered down to the requested subset in FilterAccessorsByFields (:447-453, the StringComparer.OrdinalIgnoreCase match at :452).
    • CamelCaseName is computed once at construction with CamelCase.ConvertName(prop.Name) (:61, the JsonNamingPolicy.CamelCase field held at :43) and becomes the ExpandoObject key, so the shaped payload matches the JSON casing a typed DTO would produce.
    • GetValue is the compiled getter, invoked once per property per row: in ShapeData (:75-87, the invocation at :83) and in ShapeCollectionData (:96-117, the invocation at :110).
  • Why it's built this way: private keeps a hot-path implementation detail out of the public surface; the struct plus record combination gives an allocation-free value carrier that is cheap to store in the cached arrays.
  • Where it's used: exclusively inside QueryFieldService. Two caches hold it: AccessorCache (ConcurrentDictionary<Type, PropertyAccessor[]>, :42), populated once per entity/DTO type by GetAccessors<TEntity> (:48-65), and ShapedAccessorCache (ConcurrentDictionary<(Type EntityType, string Fields), PropertyAccessor[]>, :465), which holds the pre-filtered subset for a given fields= request. Both are read by GetShapedAccessors (:471-496), which returns the full array when no field list was given (:476-477) and, once ShapedAccessorCache has reached the MaxCacheEntries cap of 512 (:39), filters per request rather than admitting another client-shaped key (:489-490).

AmbientScope

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryTagScope.cs:61 · Level 0 · class (private, sealed, nested)

  • What it is: the disposable handle QueryTagScope.Begin returns for a genuinely nested scope: an IDisposable that restores whatever ambient value was in effect before the scope opened.
  • Depends on: System.IDisposable only; it is a private nested class of QueryTagScope and has no dependency outside it.
  • Walkthrough: a primary constructor captures previous (QueryTagScope.cs:61), the ambient value before this scope opened; Dispose() (:63) writes it straight back into QueryTagScope's AmbientHandler.Value, unwinding the nesting.
  • Why it's built this way: keeping the restore logic in a tiny disposable, rather than a try/finally at each call site, lets QueryTagScope.Begin hand back a uniform IDisposable regardless of whether the scope is nested; the outermost, by far the most common, case never allocates one at all (see QueryTagScope's shared OutermostScope handle).
  • Where it's used: constructed only inside QueryTagScope.Begin (QueryTagScope.cs:52) when a scope is already open; not referenced anywhere else.

QueryFieldContract

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryFieldContract.cs:34 · Level 0 · class (sealed)

  • What it is: the allow-list of field names a client-supplied sort column or filter key may resolve against when the caller has not already remapped it through DTOToEntityPropertyMap. It also caps how many navigation segments ("Category.Name") a resolved path may carry.
  • Depends on: System.Reflection (building a contract from a DTO's public properties), System.Collections.Frozen (the FrozenSet<string> backing store); consumed by EntityQueryParameters<TEntity>'s FieldContract property and read by QueryFieldService and QueryFilterService.
  • Concept introduced, closing the sort/filter injection gap. [Rubric §17, Security] assesses whether user-controlled input can widen what the server queries. Before this contract, a client-supplied sort column or filter key with no DTOToEntityPropertyMap entry was resolved directly against the entity's own properties (SEC-Common-25, SEC-ADC-09), which let a client sort or filter on any entity member, including ones the response never exposes. QueryFieldContract closes that gap by requiring the key to appear in an explicit set: either the response DTO's own public property names (For<TContract>()/For(Type), QueryFieldContract.cs:70-88, reflected once per type and cached in ContractNames) or a server-authored list for a DTO that redacts a field per role (ForNames, :97-101).
  • Walkthrough:
    • MaxNavigationDepth = 3 (:56), the deepest a navigation path may go, counting its root; the doc comment (:50-55) frames each extra segment as another join in the emitted SQL.
    • For<TContract>() / For(Type contractType) (:70-88), the reflected contract: public instance property names, compared case-insensitively, cached per type in the static ContractNames dictionary (:58) so the reflection cost is paid once.
    • ForNames(IEnumerable<string> names) (:97-101), a contract limited to an explicit list, for a DTO field that is declared but redacted per role and so must never be orderable or filterable even though it exists on the type.
    • Contains(string? name) (:109), whether a name is in the admitted set.
    • AllowsClientKey(string? clientKey) (:117-120), the stricter check a raw client key must pass: it must name a contract field and must not itself be a navigation path (no . in it), so a client can never dot into a related entity that DTOToEntityPropertyMap did not explicitly authorize.
    • IsWithinNavigationDepth(string? entityPath) (:129-151), a static check applied to both server-authored map entries and client keys: it walks the string counting . characters and refuses a path once the segment count exceeds MaxNavigationDepth, so a pathological map entry cannot emit an unbounded join chain either.
  • Why it's built this way: an allow-list built from the response contract itself needs no separate maintenance: the DTO's own shape is the source of truth for what may be sorted or filtered on, and the frozen, cached set keeps the check allocation-light on the hot path. The depth ceiling is a second, independent defense: even a legitimate map entry cannot buy an unbounded join chain. ADR-034 records the generic read layer this contract now hardens.
  • Where it's used: constructed by EntityQueryService<TEntity, TEntityDTO, TIdentifierType> and set on EntityQueryParameters<TEntity>.FieldContract; consulted by QueryFieldService.ApplySorting and QueryFilterService.ApplyFilters whenever a key is not already covered by DTOToEntityPropertyMap; exercised directly by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Query/QueryFieldContractSecurityTests.cs.

PageWindow

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/PageWindow.cs:23 · Level 0 · record struct (readonly)

  • What it is: the value PagingMath.Clamp returns: the page a request resolves to once it has been clamped, carrying both the page number and page size actually served and the Skip/Take pair that reads it (PageWindow.cs:5-8).
  • Depends on: nothing first-party; System.Runtime.InteropServices for the [StructLayout(LayoutKind.Auto)] attribute (PageWindow.cs:1, :22).
  • Concept: one value for two consumers. [Rubric §15, Best Practices & Code Quality] assesses whether a subtle rule is computed once rather than re-derived per call site; the remarks (PageWindow.cs:9-13) state the rule this record enforces: the query takes Skip and Take, the pagination metadata takes PageNumber and PageSize, and neither re-derives the clamp, so a caller reports exactly the page it read.
  • Walkthrough: four positional members on a readonly record struct (PageWindow.cs:23):
    • PageNumber, the one-based page served, never below 1 (PageWindow.cs:14).
    • PageSize, the page size served, always within [1, maxPageSize] (PageWindow.cs:15).
    • Skip, the rows to skip (PageWindow.cs:16).
    • Take, normally equal to PageSize, or 0 for a page beyond the reachable offset range, which materializes the empty page that page actually holds. PageSize keeps the clamped request in that case, so the metadata never advertises a zero page size (PageWindow.cs:17-21).
  • Why it's built this way: a bare Take of 0 (the unreachable-offset sentinel) cannot double as the reported page size, so the served page number and size travel beside the offset and the read and its metadata come from one call. A readonly record struct keeps that return allocation-free.
  • Where it's used: produced only by PagingMath.Clamp (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/PagingMath.cs:33). Consumed by EntityQueryPipeline's ApplyPaging, which reads window.Skip and window.Take (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:276-281), and by EntityQueryService<TEntity, TEntityDTO, TIdentifierType>'s BuildPaginationMetadata, which reads window.PageSize and window.PageNumber (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:853-858).

BestEffort

MMCA.Common.Application · MMCA.Common.Application.Services.Resilience · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Resilience/BestEffort.cs:25 · Level 1 · class (public, static)

  • What it is: the framework's one sanctioned way to run a side effect that must never fail its caller: a cache eviction after a committed command, a fire-and-forget notification, an eviction broadcast onto the bus. It awaits the action and converts any non-cancellation failure into exactly one Warning log plus one metric increment.
  • Depends on: BestEffortLog (the Warning), BestEffortMetrics (the counter); Microsoft.Extensions.Logging (ILogger).
  • Concept introduced, the deliberate swallow, and why it needs a single home. [Rubric §29, Resilience & Business Continuity] assesses whether a failure in a non-essential path can take down an essential one: the real work (the command, the transaction, the HTTP response) has already succeeded by the time these side effects run, so letting one throw would roll back, retry, or 500 an operation that was correct. [Rubric §15, Best Practices & Code Quality] is the other half: a bare catch (Exception) { } is a code smell precisely because it is usually silent, and the analyzers flag it (CA1031, S2221). Routing every swallow through one helper makes the swallow explicit, logged, and counted, which is what turns it from a smell into a policy. The catch arm carries a scoped #pragma warning disable CA1031 with its justification (BestEffort.cs:65, restored at :67), and the inline comment at BestEffort.cs:69-70 says the same: the broad catch is the contract, not an oversight. [Rubric §13, Observability & Operability] covers the output side, one Warning plus one counter increment per failure.
  • Walkthrough: one method, ExecuteAsync(string operation, ILogger logger, Func<CancellationToken, Task> action, CancellationToken cancellationToken = default) (BestEffort.cs:45-49):
    • Guards first: ArgumentException.ThrowIfNullOrWhiteSpace(operation) and two ArgumentNullException.ThrowIfNull calls (BestEffort.cs:51-53). A programming error in the call itself still throws; only the action's failures are swallowed (pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Resilience/BestEffortTests.cs:132).
    • await action(cancellationToken).ConfigureAwait(false) (BestEffort.cs:57), the action is genuinely awaited, so this is not a fire-and-forget Task the runtime might lose.
    • catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } (BestEffort.cs:59-64), the one exception that is not swallowed. The filter is the load-bearing detail: it rethrows only when the caller's own token is the reason, so a host shutdown or an abandoned request unwinds promptly, while an action that cancels itself for an unrelated reason falls through to the swallow arm (BestEffortTests.cs:99 and :118, one test per side of that distinction).
    • catch (Exception ex) (BestEffort.cs:66-73, the catch line itself bracketed by the CA1031 pragma pair at :65 and :67), the terminal arm: BestEffortMetrics.RecordFailure(operation) then BestEffortLog.DispatchFailed(logger, operation, ex). Nothing is rethrown.
  • Why it's built this way: ADR-096 records the contract this helper is the single implementation of. The class doc (BestEffort.cs:11-17) states the caller's obligation that follows from the cancellation rule: a side effect that must outlive the request should be passed CancellationToken.None, not the request token. The framework's own output-cache eviction does exactly that, with the reason in the doc comment (the write has committed, so a client that disconnected mid-response must not abandon the cleanup): MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionExtensions.cs:60-70, with the CancellationToken.None argument at :90. Keeping operation a low-cardinality constant is the other obligation, because it becomes a metric tag (BestEffort.cs:20-22).
  • Where it's used: in the framework, the TryEvictTagsAsync extension (OutputCacheEvictionExtensions.cs:78-92, the helper call at :86) and MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1013. In ADC, the Engagement real-time, points and cache-eviction paths, all of which broadcast, award, or evict after the aggregate has already been saved. Under MMCA.ADC/Source/Modules/Engagement/: MMCA.ADC.Engagement.Application/SessionQuestions/UseCases/Submit/SubmitQuestionHandler.cs:214, MMCA.ADC.Engagement.Application/SessionQuestions/UseCases/Moderate/ModerateQuestionHandler.cs:146, MMCA.ADC.Engagement.Application/SessionQuestions/DomainEventHandlers/SessionQuestionUpvoteChangedHandler.cs:53, MMCA.ADC.Engagement.Application/LivePolls/DomainEventHandlers/LivePollVoteChangedHandler.cs:51, MMCA.ADC.Engagement.Application/Points/DomainEventHandlers/SessionQuestionSubmittedPointsHandler.cs:81, the bookmark eviction drain MMCA.ADC.Engagement.Infrastructure/Caching/BookmarkCacheEvictionProcessor.cs:62, and the SignalR publish processor MMCA.ADC.Engagement.Infrastructure/Live/LiveChannelPublishProcessor.cs:133. The Conference module's user integration-event handlers use it too (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Users/IntegrationEventHandlers/UserRegisteredHandler.cs:124, UserDeletedSpeakerErasureHandler.cs:100). Its own behavior is pinned by BestEffortTests (BestEffortTests.cs:13).
  • Caveats / not-in-source: nothing here retries. A swallowed side effect is gone, not queued, so anything that must eventually happen belongs in the outbox (ADR-003) rather than here.

PagingMath

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/PagingMath.cs:20 · Level 1 · class (public, static)

  • What it is: the one place a page number and page size are turned into the page actually served and a Skip/Take pair. A single static Clamp method that floors the page size, floors the page number, computes the offset in 64-bit, and refuses to hand back an offset that cannot fit in an int.
  • Depends on: PageWindow, its return type; otherwise pure BCL arithmetic (Math.Clamp, Math.Max), which is why it can be shared by the pipeline and by hand-written handlers alike.
  • Concept introduced, arithmetic overflow as a production bug class. [Rubric §12, Performance & Scalability] assesses whether reads are bounded and paginate correctly at the edges of their input range; [Rubric §15, Best Practices & Code Quality] assesses whether a subtle rule is expressed once rather than re-derived per call site. Both apply literally here. The naive expression (pageNumber - 1) * pageSize is a 32-bit multiply: for page numbers near int.MaxValue it overflows and wraps negative, and a negative Skip is not a benign no-op, because SQL Server rejects a negative OFFSET outright, so the request surfaces as a 500 instead of the empty page that page genuinely holds. The type's remarks (PagingMath.cs:6-19) record that this logic previously lived only inside EntityQueryPipeline, so handlers paginating their own queryable each re-derived it in 32-bit and kept the overflow. The rule the doc states: callers route through here rather than open-coding the multiply.
  • Walkthrough: one method, PageWindow Clamp(int pageNumber, int pageSize, int maxPageSize) (PagingMath.cs:33):
    • var take = Math.Clamp(pageSize, 1, Math.Max(maxPageSize, 1)); (PagingMath.cs:38), the page size is clamped into [1, maxPageSize], so a zero or negative size cannot become Take(0) or a negative Take, and the inner Math.Max keeps the clamp range valid even if a caller passes a zero ceiling.
    • var page = Math.Max(pageNumber, 1); (PagingMath.cs:39), a zero or negative page number is treated as page 1 rather than becoming a negative Skip. The comment above both lines (PagingMath.cs:35-37) explains why neither can be assumed away: these values arrive from callers outside the API boundary's [Range] attributes.
    • long skip = (long)take * (page - 1); (PagingMath.cs:41), the offset is computed in 64-bit, so the multiply itself cannot wrap.
    • The return (PagingMath.cs:43-45): a page beyond the reachable offset range yields new PageWindow(page, take, Skip: 0, Take: 0), which materializes the empty page that page actually holds instead of throwing or erroring, while the page number and size still describe the request; otherwise new PageWindow(page, take, (int)skip, take). See PageWindow for why both halves travel together.
  • Why it's built this way: a static, dependency-free helper is the cheapest way to make a shared invariant unavoidable; the framework pipeline, the pagination metadata and every hand-written paginating handler call the same method, so the overflow cannot be reintroduced in one of them.
  • Where it's used: EntityQueryPipeline's private ApplyPaging (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:276-279, passing MaxUnboundedResultLimit as the ceiling) and EntityQueryService<TEntity, TEntityDTO, TIdentifierType>'s BuildPaginationMetadata, with the same ceiling (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:853); the two framework notification read handlers that paginate their own joined queryable, GetMyNotificationsHandler (.../Notifications/UserNotifications/UseCases/GetInbox/GetMyNotificationsHandler.cs:32, ceiling 500 at :21) and GetNotificationHistoryHandler (.../Notifications/PushNotifications/UseCases/GetHistory/GetNotificationHistoryHandler.cs:30, ceiling 500 at :21); the view-as grant listing in both its EF store and its in-memory test double, ceiling ViewAsGrantListRequest.MaxPageSize (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFViewAsGrantStore.cs:132, MMCA.Common/Source/Hosting/MMCA.Common.Testing/Support/InMemoryViewAsGrantStore.cs:74); and two ADC handlers that page their own queries, the bookmarks read under BR-11's 500-row cap (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/UserSessionBookmarks/UseCases/GetUserBookmarks/GetUserBookmarksHandler.cs:31) and the points read with a ceiling of 100 (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Points/UseCases/GetMyPoints/GetMyPointsHandler.cs:52, constant at :32). Covered directly by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Query/PagingMathTests.cs:12, including the far-page case (PagingMathTests.cs:68) and the largest non-overflowing page (PagingMathTests.cs:77), which is the [Rubric §14, Testability] payoff of extracting the arithmetic into a pure function.

EntityQueryParameters<TEntity>

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryParameters.cs:12 · Level 0 · record (sealed)

  • What it is: an immutable parameter object that bundles every input the read pipeline needs into one value: specification criteria, dynamic filters, sort column/direction, field projection, pagination, the two navigation-include flags, and the DTO-to-entity property map.
  • Depends on: System.Linq.Expressions (the Criteria expression), System.Collections.Frozen (the default empty DTOToEntityPropertyMap), QueryFieldContract (the optional FieldContract). Consumed by IEntityQueryPipeline and its implementation EntityQueryPipeline.
  • Concept introduced, the parameter object. [Rubric §15, Best Practices & Code Quality] assesses whether long, order-sensitive argument lists are replaced by a named, self-documenting shape; the query pipeline's ExecuteAsync would otherwise take eight-plus positional arguments, so they collapse into one record with named init properties. Being a sealed record with all-init members makes it immutable once built (the primer's required/init immutability convention), so the same parameters can be passed down the pipeline without any stage mutating them, and the same object can feed either of the pipeline's two execution methods.
  • Walkthrough: eleven init-only properties, all optional (nullable or defaulted):
    • Expression<Func<TEntity, bool>>? Criteria (EntityQueryParameters.cs:15), the specification predicate (e.g. an authorization filter) applied server-side before materialization.
    • Dictionary<string, (string Operator, string Value)>? Filters (EntityQueryParameters.cs:18), the dynamic user-supplied filter map (property name to operator/value pair) that QueryFilterService turns into Where clauses.
    • string? SortColumn / string? SortDirection (EntityQueryParameters.cs:28, EntityQueryParameters.cs:31), the sort column and "asc"/"desc" direction consumed by QueryFieldService.ApplySorting.
    • string? Fields (EntityQueryParameters.cs:34), the comma-separated sparse-fieldset projection list.
    • int? PageNumber / int? PageSize (EntityQueryParameters.cs:37, EntityQueryParameters.cs:40), 1-based pagination; both must be present for the pipeline to treat the query as paginated (EntityQueryPipeline.cs:81, :170, :223), which is also what decides whether the key tie-break is appended to the sort.
    • bool IncludeFKs / bool IncludeChildren (EntityQueryParameters.cs:43, EntityQueryParameters.cs:46), whether FK reference navigations and/or child-collection navigations were requested.
    • IReadOnlyDictionary<string, string> DTOToEntityPropertyMap (EntityQueryParameters.cs:52), maps DTO property names to entity property paths (e.g. "CategoryName" to "Category.Name") so filtering and sorting can use DTO-facing names even when they differ from the entity's own properties; it defaults to FrozenDictionary<string, string>.Empty so callers that do not need remapping can omit it.
    • QueryFieldContract? FieldContract (EntityQueryParameters.cs:60), the response contract a client-supplied sort column or filter key must belong to when DTOToEntityPropertyMap does not cover it (SEC-Common-25, SEC-ADC-09). null leaves the pipeline resolving names against the entity, the pre-hardening behavior, which is only correct for a caller whose keys are server-authored rather than client-supplied. See QueryFieldContract.
  • Why it's built this way: threading one immutable value through a multi-stage pipeline keeps each stage's signature stable and its inputs unambiguous, and the frozen-empty default keeps the common no-remapping case allocation-light (the generic read layer's rationale is ADR-034).
  • Where it's used: constructed by the concrete EntityQueryService<TEntity, TEntityDTO, TIdentifierType> from the controller's query arguments, twice: once on the list path (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:373-386) and once in the shared BuildQueryAsync used by the by-id path (EntityQueryService.cs:790-802). It is then handed to EntityQueryPipeline as the third argument of ExecuteAsync (EntityQueryService.cs:409) or the second of ExecuteProjectedAsync (EntityQueryService.cs:400).

QueryTagScope

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryTagScope.cs:20 · Level 1 · class (public, static)

  • What it is: an ambient, AsyncLocal-backed carrier for the name of the use case currently executing, so a repository or a logging decorator deep in the call stack can tag its work with the handler name without that name being threaded through every method signature.
  • Depends on: System.Threading.AsyncLocal<T> only; its private nested handle type is AmbientScope.
  • Walkthrough:
    • AmbientHandler (:22), the backing AsyncLocal<string?>.
    • Current (:309), the name carried by the innermost open scope, or null when nothing is open (a background service, a seeder, a directly-constructed repository in a test).
    • Begin(string? handlerName) (:321-334): captures the previous ambient value, sets the new name only when handlerName is non-null/non-whitespace (:325-328, so a caller never has to guard the call site), then returns a handle that restores previous on dispose. The doc comment on the return (:330-332) states the allocation trade-off: the overwhelmingly common case, the outermost scope of a request whose previous is null, is served by the single shared OutermostScope instance (:340), so opening a scope allocates nothing on the hot path; only a genuinely nested scope (an internal command executed inside another handler) pays for an AmbientScope object.
  • Why it's built this way: AsyncLocal flows the value across await boundaries within the same logical call, which a plain field or a ThreadStatic cannot do reliably under async/await; sharing one instance for the outermost case is a deliberate allocation trade-off, since that case dominates in practice.
  • Where it's used: opened by LoggingCommandDecorator and LoggingQueryDecorator around a handler's execution; read by EFReadRepository, SpecificationEvaluator, and QueryTags to tag emitted queries with the active use case's name; exercised by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/SpecificationEvaluatorTests.cs.

QueryFieldService

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/QueryFieldService.cs:16 · Level 3 · class (sealed, all members static)

  • What it is: the read-side utility that owns four jobs: field validation, data shaping (sparse-fieldset projection onto ExpandoObject), dynamic sorting (including the pagination tie-break), and server-side field selection (building an EF Select expression). It caches reflected metadata, compiled getters, and compiled projections per type so that work is paid once per process, not once per request.

  • Depends on: Result, Error, PropertyAccessor (its own nested struct), DynamicQueryConfig, QueryFieldContract; System.Linq.Dynamic.Core, System.Dynamic (ExpandoObject), System.Reflection, System.Text.Json, System.Collections.Concurrent, System.Threading (Lock).

  • Concept introduced, sparse fieldsets and a four-cache metadata layer. [Rubric §9, API & Contract Design] (assesses whether clients can ask for exactly the data they need): a fields=id,name request narrows both the SQL SELECT and the JSON payload. [Rubric §12, Performance & Scalability]: four static ConcurrentDictionary caches back everything.

    • PropertiesCache (Type -> PropertyInfo[], :48) for the validation and projection paths.
    • AccessorCache (Type -> PropertyAccessor[], :49) for the shaping path, built by GetAccessors<TEntity> (:55-72), which compiles one Expression.Lambda<Func<object, object?>> per property (:63-67) and pre-computes the camelCase name (:68).
    • ProjectionCache ((Type, string Fields) -> LambdaExpression?, :423) so the MemberInit tree is built once per (entity, field set) instead of per request. Its remarks (:408-422) explain that a null value is cached deliberately: it records "this field set projects nothing writable", so the miss is not recomputed on every subsequent request.
    • ShapedAccessorCache ((Type, string Fields) -> PropertyAccessor[], :697) so a repeated fields= request reuses the filtered accessor array instead of re-filtering per call.

    The keys of the last two are normalized by NormalizeFieldsKey (:744-745), which uppercases and sorts the field names so "name,id" and "Id, Name" share one entry rather than multiplying the cache by however many spellings callers happen to send. The hot-path GetOrAdd calls pass static lambdas and thread state through the overload's extra argument (:56, :58, :392-395, :733-736), so no closure is allocated per call.

  • Concept introduced, the client-keyed cache cap. [Rubric §11, Security] (assesses whether a caller can grow process-lifetime state at will) and [Rubric §12] both apply to private const int MaxCacheEntries = 512 (:39). The two field-set caches are keyed partly by the raw fields= string, and an entity with N properties has up to 2^N distinct subsets, so unlike the type-keyed caches the key space is not bounded by the number of entity types (the remarks spell this out at :22-38). There is deliberately no LRU: past the cap each cache simply stops admitting entries and the request takes the uncached path (projection is skipped, accessors are filtered per request), which is correct and only slightly slower, rather than paying eviction bookkeeping on every lookup.

  • Concept introduced, an exact cap under concurrency. A bare Count check followed by GetOrAdd lets several threads that all saw room add at once, so the cap would only be approximate. private static readonly Lock CacheAdmissionLock (:46, doc at :41-45) serializes admission to both field-set caches, making the count check and the add one step so MaxCacheEntries is an exact bound. The lock is taken on a miss only, in a double-checked shape: a lock-free TryGetValue hit returns first (:374, :715-716); a cache already at the cap answers without the lock, since nothing will be admitted (:382-383, :722-723); otherwise, inside the lock, the key is re-read and the cap re-checked before the GetOrAdd (:385-397, :725-737). [Rubric §12] (hits stay contention-free) and [Rubric §11] (the bound a client cannot exceed is now exact).

  • Walkthrough (members in teaching order)

    • ShapeData<TEntity>(entity, fields) (:82-94) and ShapeCollectionData<TEntity>(entities, fields) (:103-124): resolve accessors through GetShapedAccessors (:84, :107), then fill an ExpandoObject keyed by CamelCaseName (:90, :117). An empty field list means all properties (GetShapedAccessors, :708-709).
    • ApplySorting<TEntity> (:168-197) is a single public overload whose fieldContract parameter is required: its doc comment states there is deliberately no overload that omits the argument, so the choice is always visible at the call (:140-145). It resolves the sort column through ResolveSortExpression (:177), then emits query.OrderBy(Filtering.DynamicQueryConfig.Parameterized, BuildOrdering(...)) (:181-183). When no valid sort column survives it falls back to the optional defaultSort lambda (:186-192) and, failing that, to the tie-break key alone (:194-196).
    • ResolveSortExpression<TEntity> (:306-335) is the security-relevant half, hardened by a QueryFieldContract parameter (SEC-ADC-09). It first trims the column (:314-316), so a padded name that passed ValidateSortColumn is not silently ignored here. A server-authored map entry then wins outright (:319-322); an unmapped name is refused immediately when a fieldContract was supplied and does not declare it (:323-326, AllowsClientKey), and otherwise (a null contract, the explicit entity-only opt-out) is accepted only when reflection finds a real public property of the entity, matched with BindingFlags.IgnoreCase (:327-332). Either way the resolved path is then refused past QueryFieldContract.MaxNavigationDepth segments (:334, SEC-Store-13). Anything refused returns null and never reaches Dynamic LINQ.
    • BuildOrdering (:342-351) turns the resolved expression plus "asc"/"desc" into the Dynamic LINQ clause and appends ", {tieBreakProperty} ascending" unless the caller already sorted by that very column, because repeating a key in an ORDER BY is redundant and some providers reject it outright.
    • ApplyFieldSelection<TEntity> (:362-403): returns the query untouched for an empty field list, otherwise pulls the compiled projection out of ProjectionCache on the lock-free TryGetValue hit path, skips projection entirely once the cache is at its cap, admits a new entry under CacheAdmissionLock on a miss below the cap (:385-397), and applies the lambda as query.Select(...) (:400-402). BuildProjection<TEntity> (:425-447) is the builder: it keeps only writable properties that match the field set (p.CanWrite), since EF cannot translate a MemberInit that assigns a read-only member, returns null when nothing survives, and otherwise builds new TEntity { Prop = e.Prop, ... } so the projection is pushed into the SQL SELECT.
    • Two Validate overloads. Validate<TEntity>(fields, allowWriteableFields = false) (:461-462) consults no DTO-to-entity map and no response contract; its doc comment points any name that is client input later resolved through a map at the other overload (:453-454). The fully hardened Validate<TEntity>(fields, dtoToEntityPropertyMap, allowWriteableFields, fieldContract) (:503-508, SEC-ADC-09) takes every argument with no default. Both delegate to the shared ValidateFields (:552-574), which loops the requested field set through ValidateSingleField (:580-640) per name. ValidateSingleField checks, in order: a map entry wins unconditionally and is never reflected over (:589-601), except that a mapped path deeper than QueryFieldContract.MaxNavigationDepth is rejected too (:591-598, SEC-Store-13); an unmapped name is refused when a fieldContract was supplied and does not declare it (:607-616, the RESPONSE contract, not the entity, decides what a client may name); and only then does it fall through to the entity-reflection check, existence (:618-630) plus, when allowWriteableFields is false, not read-only (:632-639). All offenders accumulate into one aggregate Result.
    • ValidateSortColumn<TEntity>(sortColumn, dtoToEntityPropertyMap, fieldContract) (:523-546) is the dedicated sort-column validator, so validation applies exactly the rules ApplySorting does. Null or blank is a success (:528-529, default order). A comma-separated list is refused with Error.InvalidEntityField and the message "Only one sort column is accepted." (:531-538), because sorting honors one column and the field-list validator would split and trim a list the sort then ignores. Otherwise the trimmed name goes through ValidateSingleField with allowWriteableFields: true (:541), since a computed column may still be sortable, and any errors become one failure (:543-545).
    • ValidateSortDirection (:647-666): accepts only "asc", "desc", or null/empty, and returns an Error.Validation("Error.InvalidSortDirection", ...) failure otherwise.
    • Private helpers: ParseFields (:668-672) splits the comma list into a case-insensitive HashSet; GetProperties<TEntity> (:674-677) reads through PropertiesCache; FilterAccessorsByFields (:679-685) narrows an accessor array; GetShapedAccessors (:703-738) is the cached front door to it, filtering per request instead of caching once ShapedAccessorCache is at its cap (:722-723, re-checked under the lock at :730-731).
  • Concept introduced, gating client-named sort/filter/lookup columns on the response contract, not the entity. [Rubric §11, Security]: QueryFieldContract (SEC-ADC-09, SEC-Common-24, SEC-Common-25, SEC-Store-13) is the allow-list a client-supplied name must clear before an unmapped name is even reflected over, so a caller can no longer order, filter, or project by an entity column the response never carries (a redacted or audit-only field) just because it happens to exist on TEntity. A server-authored map entry is still the escape hatch for a navigation path or Dynamic LINQ expression no DTO property names, capped instead at MaxNavigationDepth. fieldContract: null is an explicit opt-out to the entity-only check, correct only for server-authored names (:140-145, :495-501). On ApplySorting, the hardened Validate and ValidateSortColumn the parameter has no default and no overload omits it, so every caller states its choice at the call site; only the two-argument Validate, which takes no map either, skips the contract.

  • Why it's built this way: the sort path carries the security argument. The doc comment on ApplySorting names the three risks the property (and now contract) check closes: inferring hidden-column data through a nested path, forcing an unindexed sort, and turning a Dynamic LINQ parse error into a 500. Server-authored map entries may be navigation paths or expressions, client-supplied strings may not. [Rubric §11, Security] and [Rubric §12, Performance & Scalability]. The tieBreakProperty parameter exists for a different failure: the remarks explain that Skip/Take over a non-total ORDER BY is undefined, so the same row can appear on two consecutive pages while another appears on neither, from data that never changed. The pipeline passes the entity key, which is server-supplied and therefore does not widen what a caller can order by.

  • Where it's used: Validate, ValidateSortColumn and ValidateSortDirection are called by EntityQueryService<TEntity, TEntityDTO, TIdentifierType> before the database is touched (the list read's ValidateSortColumn and ValidateSortDirection at EntityQueryService.cs:350-351, the former passing its FieldContract; the lookup name check at :460; the fields validation in the service's private ValidateFields at :693-698; and the cursor read's ValidateSortColumn at :596); ShapeCollectionData and ShapeData are called after mapping (EntityQueryService.cs:426, :571); ApplyFieldSelection is called inside EntityQueryPipeline (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:196, :234), and ApplySorting is reached through the internal ApplyListSorting (QueryFieldService.cs:214-243), which the pipeline's private sort helper calls (EntityQueryPipeline.cs:254, invoked at :83, :168, :215). ApplyListSorting lets a resolvable request sort win (QueryFieldService.cs:223-227) and otherwise applies the specification's server-authored DefaultOrdering one typed step at a time (:229-230, ApplyOrderingStep at :259-275), appending the tie-break key unless that ordering already sorts by it (:234-242). Outside the query layer, EntityControllerBase checks ValidateSortDirection (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:428) and the CSV exporter shapes rows with ShapeData (MMCA.Common/Source/Presentation/MMCA.Common.API/Export/EntityCsvExporter.cs:326).

  • Caveats / not-in-source: the class is sealed but every member is static, so it is never instantiated or injected; treat it as a static utility despite the shape. One public overload carries a SuppressMessage for the public-API analyzer's optional-parameter rules: the two-argument Validate for RS0027 (:460), whose justification records a grandfathered overload whose signature cannot change without a breaking change (the RS0026/RS0027 baseline).


IEntityQueryPipeline

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/IEntityQueryPipeline.cs:10 · Level 4 · interface

  • What it is: the contract for the multi-step read pipeline. It has two execution methods: the entity path, which applies includes, criteria, filters, sorting, pagination and field projection and returns materialized entities plus the total row count, and the projected path, which runs the same filtering/sorting/paging over entity rows but lets the provider return a projected shape directly.
  • Depends on: EntityQueryParameters<TEntity> (the input bundle), NavigationMetadata (supported vs unsupported includes), AuditableBaseEntity<TIdentifierType> (the TEntity constraint); System.Linq (IQueryable).
  • Concept introduced, the read pipeline behind one abstraction. [Rubric §5, Vertical Slice] assesses whether a capability lives behind one focused abstraction rather than smeared across callers; every read endpoint's list logic funnels through this interface. Both methods return Task<(IReadOnlyCollection<T> Items, int TotalCount)> (IEntityQueryPipeline.cs:23, :58), so the page and the count needed to build pagination metadata come back in one call.
  • Walkthrough
    • ExecuteAsync<TEntity, TIdentifierType> (IEntityQueryPipeline.cs:23-30), constrained where TEntity : AuditableBaseEntity<TIdentifierType> and where TIdentifierType : notnull (:29-30), takes the starting IQueryable<TEntity> (:24), the NavigationMetadata classification (:25), the EntityQueryParameters<TEntity> (:26), and a Func<IReadOnlyCollection<TEntity>, NavigationMetadata, bool, bool, CancellationToken, Task> navigationPopulator callback (:27) the pipeline invokes to manually load unsupported navigations (the two bools are includeFKs/includeChildren). Passing the populator as a delegate keeps the pipeline in the Application layer while the actual populator lives in Infrastructure (ADR-002, G11).
    • ExecuteProjectedAsync<TEntity, TResult, TIdentifierType> (IEntityQueryPipeline.cs:58-64) takes the same base query and parameters plus a Func<IQueryable<TEntity>, IQueryable<TResult>> project (:61) that rewrites the entity queryable into the projected one. Its remarks (:37-49) are the contract that matters: this path exists for reads whose result type has a registered IEntityDTOProjector, it skips two costs of the entity path (selecting every entity column, and mapping each materialized row), and it handles server-side navigations only. There is no populator hook, because a projection cannot be post-processed row by row, so a query with cross-source includes must use ExecuteAsync instead; navigation includes are not applied here either, since the projection itself decides what the provider joins and selects.
  • Why it's built this way: abstracting the pipeline behind an interface lets the query service depend on the behavior, not the concrete steps, and lets the navigation-population strategy be injected as a delegate rather than a hard dependency (Clean Architecture, [Rubric §3]). Two methods rather than one flag keeps the two contracts honest: the projected one cannot even be handed a populator, so the unsupported combination is unrepresentable.
  • Where it's used: implemented by EntityQueryPipeline; injected into and called by the concrete EntityQueryService<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:38, with the two call sites at :397-402 and :406-411).

TrackedView

MMCA.Common.Application · MMCA.Common.Application.Services.Query (private, nested in EntityQueryService<TEntity, TEntityDTO, TIdentifierType>) · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:745 · Level 4 · class (private, sealed, nested)

  • What it is: a tracked copy of a specification's scope (criteria, includes, soft-delete scope), built when a list or by-id read asks for tracking but the caller's specification did not (class doc, EntityQueryService.cs:739-744).
  • Depends on: QuerySpecification<TEntity, TIdentifierType> (the base class, for its Criteria override, AddInclude, WithSoftDeleted and WithTracking) and ISpecification<TEntity, TIdentifierType> (the scope it copies); System.Linq.Expressions (BCL).
  • Concept introduced, the request's tracking choice wins. [Rubric §15, Best Practices & Code Quality] assesses whether a caller's explicit choice is honored rather than silently dropped. A specification fixes its own AsTracking flag (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/QuerySpecification.cs:77), so a request that passes asTracking: true with an untracked specification would otherwise lose the tracking it asked for. ListBaseQuery resolves this by wrapping the specification in a TrackedView whenever tracking was requested and the specification is not already a tracked QuerySpecification (EntityQueryService.cs:732-736); a specification that already tracks is passed through unchanged.
  • Walkthrough: one constructor and one property.
    • The constructor (EntityQueryService.cs:747-761) copies Criteria = scope.Criteria (:749). When the scope is a shaped QuerySpecification (:751), it re-adds every entry of its IncludePaths through AddInclude (:753-754) and, if the scope set IgnoreQueryFilters, calls WithSoftDeleted() (:756-757), so a soft-delete scope is not lost. It then calls WithTracking() (:760).
    • Criteria (:763) is a get-only override set once in the constructor.
    • Ordering and paging are deliberately not copied: the class doc (:741-743) records that QueryFor applies neither, and the default ordering is read from the original specification.
  • Why it's built this way: copying the scope into a new specification, rather than mutating the caller's, leaves the caller's object untouched; private keeps it an implementation detail of the service's base-query resolution.
  • Where it's used: constructed only in ListBaseQuery (EntityQueryService.cs:735), which both the list read (EntityQueryService.cs:388) and the by-id read's BuildQueryAsync (:786) call for their base query. Pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Query/EntityQuery/EntityQueryServiceSpecificationTests.cs:159 (tracking, soft-delete scope and include path carried; no ordering or Take) and its sibling at :174 (an already-tracked specification is passed through as the same instance).

ChangeFeedSpecification<TEntity, TIdentifierType>

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/ChangeFeedSpecification.cs:15 · Level 6 · class (internal, sealed)

  • What it is: the read scope of the change feed. It selects the rows changed at or after a UTC instant, ANDed with the caller's own scope, and lifts the soft-delete filter so a deleted row can be reported as a tombstone, while every other global filter, the tenant filter included, stays in force (class doc, ChangeFeedSpecification.cs:8-12).
  • Depends on: QuerySpecification<TEntity, TIdentifierType> (the base class, for its Criteria override and WithSoftDeleted), ISpecification<TEntity, TIdentifierType> (the caller's optional scope), InlineSpecification<TEntity, TIdentifierType> and AndSpecification<TEntity, TIdentifierType> (the composition), and AuditableBaseEntity<TIdentifierType> (the TEntity constraint that supplies LastModifiedOn, :16); System.Linq.Expressions (BCL).
  • Concept introduced, the tombstone read. [Rubric §8, Data Architecture] assesses whether a client can be brought up to date without a full re-read. A plain list read cannot report a deletion, because the soft-delete query filter hides the deleted row (ADR-144). This specification calls WithSoftDeleted() (ChangeFeedSpecification.cs:30), which drops the named SoftDelete filter and only that one (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/QuerySpecification.cs:134-138), so the deleted row comes back with IsDeleted set and the service can emit it as a tombstone. [Rubric §17, Security]: lifting only that one filter is what keeps a change feed from becoming a cross-tenant read.
  • Walkthrough:
    • The constructor (:27-31) takes a nullable sinceUtc and a nullable scope, assigns Criteria = BuildCriteria(sinceUtc, scope) (:29) and calls WithSoftDeleted() (:30). The Criteria override (:34) is a get-only property set once there.
    • BuildCriteria (:36-55) builds an optional time bound e => e.LastModifiedOn >= bound (:39-42, the predicate at :41) and wraps the caller's scope in a fresh InlineSpecification over scope.Criteria alone (:44-46). The parameter doc (:23-26) gives the reason for the wrap: only the scope's Criteria is used, so a scope that is itself a shaped QuerySpecification (with its own includes, ordering or paging) is accepted and its shaping is ignored.
    • A tuple switch (:48-54) composes the result: both present gives new AndSpecification(time, scoped).Criteria (:50), one present gives that one's criteria (:51, :52), and neither gives _ => true (:53), a full read.
  • Why it's built this way: expressing the feed's scope as a specification lets it run through the same repository keyset read every other paged read uses, so the feed inherits the tenant filter and the store-side paging rather than re-implementing them. A row whose LastModifiedOn is null never matches the time bound, so it appears only in a full read (since null), a limit ADR-144 records.
  • Where it's used: constructed only by EntityQueryService<TEntity, TEntityDTO, TIdentifierType> in GetChangesSinceAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:630, construction at :637), which pages it by cursor over LastModifiedOn ascending (EntityQueryService.cs:638-644) and maps only the live rows (:651). Being internal, it is not part of the package's public surface.

EntityQueryPipeline

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:14 · Level 7 · class (sealed)

  • What it is: the concrete read pipeline. The entity path runs a two-path include strategy: PATH 1 uses EF Core .Include() when the data source can JOIN (server-side), PATH 2 materializes first and loads unsupported navigations manually. A third, projected path skips entity materialization altogether. Every path applies criteria, filters, sorting and pagination, with a hard row ceiling that keeps each read bounded.
  • Depends on: IEntityQueryPipeline (the contract), IQueryableExecutor (the injected abstraction over EF's async Include/Count/ToList/AsSplitQuery, keeping this Application-layer class free of a direct EF reference), EntityQueryParameters<TEntity>, NavigationMetadata with its NavigationType enum, the filtering and field helpers QueryFilterService / QueryFieldService (both now also receive parameters.FieldContract, forwarded unchanged so a client-supplied key not covered by DTOToEntityPropertyMap is checked against the DTO's QueryFieldContract), the shared PagingMath, and AuditableBaseEntity<TIdentifierType> (the TEntity constraint).
  • Concept introduced, the unbounded-result ceiling. [Rubric §12, Performance & Scalability] assesses whether every read is bounded. The ceiling is codified as public const int MaxUnboundedResultLimit = 1000; (EntityQueryPipeline.cs:23): a defense-in-depth cap so that even an Application-layer caller that bypasses the API's page-size clamp cannot trigger an unbounded full-table load (the doc comment at :15-22 spells out that layering).
  • Concept introduced, the pagination tie-break. private const string PaginationTieBreakProperty = "Id" (EntityQueryPipeline.cs:38) is appended as a final ascending sort key on every paginated read (:86, :181, :234). Its doc comment (:25-35) gives both halves of the reasoning: the key qualifies because every entity has it, it is unique, and it is server-supplied rather than client input; and only paginated reads get it, because an unpaginated read materializes one capped set in one statement and so cannot suffer the split-across-pages incoherence, while adding an ORDER BY there would charge every unsorted list read for a sort nobody asked for. [Rubric §8, Data Architecture] and [Rubric §12]: Skip/Take over a non-total order is undefined, and the tie-break is what makes it total.
  • Walkthrough: constructed with an IQueryableExecutor (:13).
    • ExecuteAsync (:39-57) is now a thin dispatcher: it runs the shared front half (ApplyIncludesCriteriaAndFilters, :48), then routes to ExecuteWithManualNavigationAsync when there is at least one unsupported include (:53-54) and to ExecuteWithServerSideIncludesAsync otherwise (:56).
    • ApplyIncludesCriteriaAndFilters (:120-155) is that front half. PATH 1 includes (:132-143): for each supported include, call queryableExecutor.Include(...) (:135); if any supported include is a ChildCollection, switch to AsSplitQuery (:141-142). The inline comment (:137-140) documents why: paginating a single-query collection-Include truncates child rows because EF applies Skip/Take to the JOIN-expanded set, so list reads come back with empty collections while by-id reads (no Skip) work; a split query loads each collection in its own statement (the R24/§8 fix). Then server-side filtering before materialization (:145-152): apply parameters.Criteria via Where (:148-149), then the dynamic filters via QueryFilterService.ApplyFilters (:151-152, passing parameters.FieldContract as the fourth argument), so the store does as much filtering as possible while still validating any key not covered by DTOToEntityPropertyMap.
    • ExecuteWithManualNavigationAsync (:162-212): sort at the DB level with the tie-break when paginated (:176-182), keep a handle on the unpaged query (:184), then if paginated take the total count before paging and call ApplyPaging (:186-190); if not paginated, cap with .Take(MaxUnboundedResultLimit) (:195). Materialize (:198), run the navigationPopulator on the paged subset only when it is non-empty (:199-202), settle the unpaginated total via CountUnpaginatedAsync (:204-207), and finally apply field selection in memory over the materialized page (:209-211).
    • ExecuteWithServerSideIncludesAsync (:218-263): the same sort / count-before-paging / cap shape (:229-251) but applies QueryFieldService.ApplyFieldSelection on the IQueryable directly (:254) so the projection reaches the database as a MemberInit.
    • ExecuteProjectedAsync (:60-114) is the projection-pushdown path. It null-guards its arguments (:68-69), applies criteria (:73-74) and filters (:76-77), sorts with the same tie-break rule (:81-87), counts before paging when paginated (:94-95) or caps at the ceiling when not (:99), and only then calls project(query) (:106). The comment above that line (:102-105) states the ordering rule and its consequence: projecting last means filtering, sorting and paging all run over entity rows, so the provider pages exactly the rows it means to and selects only that page's columns, and navigation includes are deliberately not applied because the projection decides which columns and joins the provider emits.
    • ApplyPaging (:274-284), the shared paging step: it delegates the offset arithmetic to PagingMath.Clamp with MaxUnboundedResultLimit as the ceiling (:278-281) and returns query.Skip(skip).Take(take) (:283). The page size is therefore clamped to the ceiling here as well as at the API boundary, defense in depth (doc comment, :265-273).
    • CountUnpaginatedAsync (:291-297) guards a subtle reporting edge: for an unpaginated read the materialized count is only the truth while it stays under the ceiling; at the ceiling it is the cap itself, so the method issues a real CountAsync against the unpaged query rather than tell callers the set was exactly 1000 rows (:295-297, doc comment :286-290).
  • Why it's built this way: pushing filters and projection to the store, forcing split-query for paginated child collections, capping every path, making every paginated order total, and reporting an honest total keeps reads correct and bounded regardless of engine; injecting IQueryableExecutor keeps EF out of the Application layer (Clean Architecture), and routing the offset math through PagingMath keeps the overflow guard shared with the hand-written paginating handlers. ADR-034 records the generic read layer's trade-offs.
  • Where it's used: the sole implementation behind IEntityQueryPipeline; driven by the concrete EntityQueryService<TEntity, TEntityDTO, TIdentifierType>, which also reads MaxUnboundedResultLimit directly when it builds the response's pagination metadata (EntityQueryService.cs:845, :853).

EntityQueryService<TEntity, TEntityDTO, TIdentifierType>

MMCA.Common.Application · MMCA.Common.Application.Services.Query · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:35 · Level 8 · class

  • What it is: the reusable engine behind essentially every read endpoint in both apps: filtered, sorted, paginated, field-projected list and by-id reads for any entity. It implements IEntityQueryService<TEntity, TEntityDTO, TIdentifierType>.
  • Depends on: injected through a primary constructor (:35-40), IUnitOfWork, INavigationMetadataProvider, IEntityQueryPipeline, IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>, and INavigationPopulator<in TEntity>; optionally IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType> through the second constructor; plus IReadRepository<TEntity, TIdentifierType>, ISpecification<TEntity, TIdentifierType>, EntityQueryParameters<TEntity>, NavigationMetadata, QueryFieldService, QueryFilterService, QueryFieldContract, PaginationMetadata, PagedCollectionResult<T>, BaseLookup<TIdentifierType>, and for the cursor and change-feed reads KeysetPageRequest, KeysetCollectionResult<T>, EntityChange<TEntityDTO, TIdentifierType> and ChangeFeedSpecification<TEntity, TIdentifierType>. Constrained where TEntity : AuditableBaseEntity<TIdentifierType>, where TEntityDTO : IBaseDTO<TIdentifierType>, where TIdentifierType : notnull (:42-44).
  • Concept introduced, one generic read pipeline for every entity. [Rubric §1, SOLID] (Open/Closed: extend by subclassing and overriding, not by editing), [Rubric §9, API & Contract Design] (one filter/sort/page/fields convention across every read endpoint), [Rubric §12, Performance & Scalability] (all shaping is pushed down to the database through the pipeline), and [Rubric §15, Best Practices & Code Quality] (a new entity inherits the full read surface with no new code). The list path, the wide GetAllAsync overload (:330-435), is four steps:
    1. Validate before touching the database (:343-365). The navigation classification (BuildIncludes, :344) and the CanProject decision (:346) run first, because the fields rule depends on which path will serve the read; a QuerySpecification that asks for tracking (shape?.AsTracking, :345-346) keeps the read on the entity path just as asTracking does. Result.Combine (:348-353) of the private ValidateFields(fields, project) (:349, defined :691-699), then QueryFieldService.ValidateSortColumn for sortColumn (:350, passing the instance's PropertyMap and FieldContract; it refuses a comma-separated list (QueryFieldService.cs:531) and validates one trimmed name with the same rules ApplySorting applies, where a computed column may still be sortable), ValidateSortDirection (:351), and QueryFilterService.ValidateFilters (also passed FieldContract, :352). PropertyMap (:118-119) is DTOToEntityPropertyMap read through a case-insensitive copy made once per map instance (:121-137, cached in CaseInsensitiveMaps, :189); an override whose comparer is already OrdinalIgnoreCase is used as is (:139-144), and two keys that differ only by case throw InvalidOperationException on the first query (:129-133). ValidateFields validates the list against the DTO via QueryFieldService.Validate (allowWriteableFields: true, through PropertyMap and FieldContract, :693-694), so a DTO-only name is accepted and an entity-only name, which has no DTO accessor and would shape every row into an empty object, is refused. On the non-projected path it additionally requires each name to be a writable entity property (allowWriteableFields: false, :698), because the pipeline narrows the entity with a MemberInit before mapping. The by-id read always takes the non-projected rule (:492-494). On failure every Error is re-stamped with Source = nameof(GetAllAsync) and Target = typeof(TEntity).Name via a with expression, so the caller sees which operation and which entity produced each problem.
    2. Pack the parameters: with the NavigationMetadataProvider.BuildIncludes result from step 1 (which navigations EF can Include), pack everything (including the specification's ordering as DefaultOrdering, the PropertyMap, and FieldContract, :373-386) into an EntityQueryParameters<TEntity>, and take the base query from ListBaseQuery (:388, defined :727-737): Repository.Table when tracking is requested or TableNoTracking otherwise when there is no specification, else the repository's QueryFor view of the specification, wrapped in a TrackedView when the caller asked for tracking and the specification did not (:734-736). The comment (:367-372) records the rule: the specification scopes the base query (criteria, soft-delete scope, includes, tracking), its ordering is only the default for a request that names no sort, and its own Skip/Take is never applied.
    3. Execute on one of two paths (:390-415). When CanProject says yes, the read goes through IEntityQueryPipeline.ExecuteProjectedAsync with the projector's ProjectTo (:397-402), so the provider selects the DTO's columns directly and nothing is ever materialized as an entity. Otherwise the entity path runs ExecuteAsync with NavigationPopulator.PopulateAsync as the callback (:406-411) so cross-source navigations EF cannot join are batch-loaded after materialization (ADR-002), then maps with IEntityDTOMapper (:414).
    4. Shape only when asked, then wrap (:417-434): the DTOs are cast to object as-is unless a fields subset was requested, in which case QueryFieldService.ShapeCollectionData produces ExpandoObjects (:424-426). The comment (:417-421) explains the rule: typed DTOs already serialize to the same camelCase JSON, so paying the per-row ExpandoObject allocation and boxing only makes sense when it actually removes fields, and because shaping reflects over the runtime object it behaves identically on a mapped DTO and a projected one. The result is a PagedCollectionResult<object> (:428-432) with PaginationMetadata from BuildPaginationMetadata (:422, defined :829-859).
  • Concept introduced, projection pushdown as an optional dependency. CanProject (:717-720) gates the projected path on three conditions: a projector was registered, the caller did not ask for tracking, and there are no unsupported (cross-source) includes. The remarks (:704-716) give the reasons: a projection produces DTOs, which the change tracker has nothing to do with, and the navigation populator needs materialized rows a projection never produces. Field shaping deliberately does not disqualify. The projector arrives through a second constructor (:73-81) rather than an optional parameter, and the remarks (:55-66) state why: Microsoft.Extensions.DependencyInjection has no notion of an optional dependency, so a single constructor naming an unregistered service fails to resolve regardless of a default value. With two constructors whose parameter sets are strict supersets, the container picks the longer one when an IEntityDTOProjector is registered and the shorter one when it is not, and existing subclasses chaining to the five-argument constructor keep compiling. [Rubric §12, Performance & Scalability] (two costs skipped: selecting every entity column, and mapping each materialized row) and [Rubric §1, SOLID] (the feature is additive, nothing existing changes).
  • Concept introduced, gating client-named columns on the response contract. [Rubric §11, Security]: FieldContract (:146-166, SEC-Common-24, SEC-Common-25, SEC-ADC-09) is a protected virtual QueryFieldContract? defaulting to QueryFieldContract.For<TEntityDTO>(), so a client-supplied sortColumn, filter key, or lookup nameProperty can only name data the DTO actually carries, closing the gap where an entity column the mapper redacts (still orderable, which discloses its total order) or never exposes was reachable simply because it existed on TEntity. The doc remarks (:152-165) record the override path: narrow further with QueryFieldContract.ForNames for a per-role redaction, or return null to deliberately restore the pre-hardening entity-only behavior. LookupNameContract (:168-178) defaults to FieldContract and gates GetAllForLookupAsync specifically, with its own remarks noting it can be narrowed further, independent of the general FieldContract, to the one or two columns a lookup is meant to label rows with.
  • Walkthrough, the other read paths
    • The by-id fast path (TryGetByIdFastPathAsync, :201-221). For a plain primary-key lookup it issues a single keyed read through Repository.GetByIdAsync(typedId, includes, asTracking, ...) (:217) and skips the dynamic-filter pipeline entirely. The doc comment (:191-200) states why this exists: the pipeline would parse a string predicate and emit a TOP 1000 plus a client-side FirstOrDefault, and it notes that the repository overload runs on the filtered TableNoTracking, so soft-delete query filters still apply (unlike EF's FindAsync, which bypasses them). A miss returns Error.NotFound stamped with WithSource/WithTarget (:218-219).
    • What qualifies for it (TryGetFastPathIncludes, :243-273). Field projection, a specification, or a non-default idField disqualify (:253-258). Requested includes do not: the remarks (:227-242) explain that disqualifying on includes would leave the fast path unreachable for every entity declaring a navigation, because the REST by-id action defaults includeFKs to true, so those reads would fall back to the pipeline. The repository's include overload applies the same Include calls and auto-applies AsSplitQuery for child collections, so the two agree. Unsupported includes still disqualify (:265-269), because those are cross-source navigations only the pipeline's INavigationPopulator can batch-load. Otherwise the supported navigation names are handed back (:271).
    • TryConvertId (:280-306) converts the string id via a TypeConverter cached per identifier type in IdConverterCache (:185), catching only FormatException, NotSupportedException, and ArgumentException (:300) and returning false so a malformed id falls back to the pipeline rather than failing. The whole fast path is a targeted [Rubric §12, Performance & Scalability] optimization on the single hottest read shape in the system.
    • GetEntityByIdAsync (:482-542): validates fields (:494), tries the fast path (:510-514), and otherwise reuses the list pipeline through a synthetic Id EQUALS filter built with an OrdinalIgnoreCase comparer (:516-519) and BuildQueryAsync (:521-530), returning Error.NotFound.WithSource(nameof(GetByIdAsync)).WithTarget(...) when nothing came back (:532-539).
    • GetByIdAsync (:545-572): stringifies the typed id (throwing InvalidOperationException if ToString() returns null, :554), delegates to GetEntityByIdAsync, unwraps the outcome with Result<T>.TryGetValue(out var found) so a failure forwards its errors unchanged and the success branch holds a non-null entity without a Value! suppression (:563-564), maps that entity (:566), and applies the same shape-only-when-asked rule as the list path (:568-571).
    • GetAllForLookupAsync (:438-479): first checks LookupNameContract and rejects a nameProperty it does not declare (:444-458, SEC-Common-24: the doc comment explains that without this gate, ?nameProperty= would project ANY public entity property for every row), then validates the name with allowWriteableFields: true (:460), then delegates to the repository's lookup query, forwarding the optional where predicate and the tracking flag, and returns BaseLookup<TIdentifierType> id/name pairs for dropdowns.
    • ExistsAsync (:575-579): a thin non-virtual pass-through to Repository.ExistsAsync(where, ignoreQueryFilters, ...).
    • GetPageByCursorAsync (:589-620, remarks :582-588): the opt-in keyset read (ADR-145). It takes a KeysetPageRequest, validates its SortColumn with the same QueryFieldService.ValidateSortColumn rules as the list read (passing PropertyMap and FieldContract, :596), and re-stamps each error with Source = nameof(GetPageByCursorAsync) and the entity name (:597-606). A trimmed sort column found in the case-insensitive PropertyMap is replaced by its entity value through a with copy of the request (:608-613) before Repository.GetPageByCursorAsync runs (:615); per the remarks a mapped navigation path is refused there as Error.InvalidEntityField. Rows are mapped with DTOMapper in repository order into a KeysetCollectionResult<T> carrying the repository's NextCursor (:619). No fields shaping or projection applies on this path.
    • GetChangesSinceAsync (:630-664, remarks :622-629): the delta read (ADR-144). It wraps the caller's optional specification in a ChangeFeedSpecification<TEntity, TIdentifierType> built from the normalized since bound (:637), which per the remarks lifts the soft-delete filter only so the tenant filter stays in force, and runs one keyset read ordered by LastModifiedOn ascending (:638-644, the remarks name Id as the tie-break). Only live rows are mapped, in page order (:651); each row becomes an EntityChange<TEntityDTO, TIdentifierType> with ChangedOn = LastModifiedOn ?? CreatedOn, and a soft-deleted row is a tombstone whose Item stays default (:653-661), so none of its fields leave the service. The private ToUtc helper (:666-673) converts a Local bound and stamps an Unspecified one as UTC.
    • BuildQueryAsync (:773-810) is the shared assembler behind the by-id path: the same ListBaseQuery base query as the list read (:786), so a specification scopes both reads alike and a WithSoftDeleted() scope is not lost on the by-id read (summary :766-772), the same BuildIncludes call (:788), the same parameter object (including FieldContract = FieldContract at :801), then IEntityQueryPipeline.ExecuteAsync (:804-809).
    • Extensibility points: Repository (:91) and DTOToEntityPropertyMap (:112) are virtual, as are all the read methods, and the class is deliberately not sealed, so a module subclass can override one behavior (a scoped repository, a "CategoryName" -> "Category.Name" mapping) without reimplementing the pipeline. UnitOfWork is protected (:47) and DTOProjector is protected (:88) for subclasses that need them.
  • Why it's built this way: centralizing read mechanics means every entity gets identical filter/sort/page/projection semantics for free, and validate-before-database turns a bad fields or operator into a validation failure rather than a SQL or expression-parser error. The INavigationPopulator callback is the database-per-service extension point (ADR-002 and ADR-006): EF cannot join across physical sources, so those navigations are filled by a second batch query against the page that was actually returned. ADR-034 records the generic read layer's trade-offs.
  • Where it's used: injected as the query service of the read controllers (EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>) in both apps, and subclassed per module wherever a default must change. The canonical override is a property map: ProductEntityQueryService (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Products/ProductEntityQueryService.cs:15) chains to the five-argument constructor (:21-22) and overrides DTOToEntityPropertyMap (:48) with a property map (:31-45) whose "CategoryName" -> "Category.Name" entry (:33) sits beside variant-count, rating and creation-date keys; CategoryEntityQueryService and ADC's SpeakerEntityQueryService follow the same shape (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.Application/Categories/CategoryEntityQueryService.cs:21, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/SpeakerEntityQueryService.cs:21). Behavior is pinned by EntityQueryServiceTests, EntityQueryServiceProjectionTests, EntityQueryServiceResolutionTests, and, for the two keyset reads, EntityQueryServiceCursorTests and EntityQueryServiceChangeFeedTests.
  • Caveats / not-in-source: this class does not clamp the page size it applies (the clamp lives in EntityQueryPipeline's ApplyPaging, MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:272-282), but it does clamp the page size it reports: BuildPaginationMetadata (:714-759) recomputes the clamp rather than reading it back from PagingMath, because that helper returns a (0, 0) sentinel for an unreachable offset and reporting that take would advertise PageSize = 0 for a perfectly valid request (remarks, :715-729). Every input is floored or clamped before it reaches the validating PaginationMetadata constructor, which throws on a negative value. It floors the total at zero (:735), reports the row count actually returned as the page size for an unpaginated read (:737-748), and clamps a paginated request into [1, MaxUnboundedResultLimit] (ceiling of 1000 at MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:23). Error stamping in the by-id path always uses Source = nameof(GetByIdAsync) (:447, :484) even when GetEntityByIdAsync is called directly, a cosmetic label, not a behavior difference.

KeyCarrier<TPrincipalId>

MMCA.Common.Application · MMCA.Common.Application.Specifications · MMCA.Common/Source/Core/MMCA.Common.Application/Specifications/CrossSourceSpecification.cs:105 · Level 0 · class (private, sealed, nested in CrossSourceSpecification)

  • What it is: a private holder nested inside CrossSourceSpecification that carries the materialized principal key list, so the criteria it builds reads the keys through a property access instead of embedding the list itself as an expression-tree constant.
  • Depends on: nothing first-party. BCL only (IReadOnlyList<T>, IEnumerable<T>).
  • Concept introduced, a parameterized versus an inlined collection in EF Core. [Rubric §8, Data Architecture] assesses whether queries reach the database in a shape the engine can execute and reuse efficiently. When EF Core translates an expression tree, a value read through a member access on a constant (the shape the C# compiler emits for a captured local: a field on a closure object) is extracted as a query parameter, while a bare constant collection is inlined as literal values; the type's doc comment states that rule (CrossSourceSpecification.cs:99-104). Inlined literals mean one distinct SQL text, query plan and compiled-query cache entry per distinct key set, and the key set changes whenever the principal set does (the class doc at :20-23). A tree built by hand with Expression factory calls has no closure to capture, so the carrier object reproduces the captured-local shape explicitly.
  • Walkthrough: a primary-constructor sealed class KeyCarrier<TPrincipalId>(IReadOnlyList<TPrincipalId> keys) (:105) with one get-only property, IEnumerable<TPrincipalId> Keys (:108), initialized from the constructor argument. The property is typed IEnumerable<TPrincipalId> so it binds directly as the source argument of the Enumerable.Contains call.
  • Where it's used: only CrossSourceSpecification.BuildCriteria, which passes Expression.Property(Expression.Constant(new KeyCarrier<TPrincipalId>(keys)), nameof(KeyCarrier<>.Keys)) as the first argument of Enumerable.Contains (CrossSourceSpecification.cs:84, the reason recorded in the comment at :78-79). The resulting SQL shape is pinned by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/SqlServerQueryShapeTests.cs:35 and :46; the caveats are under CrossSourceSpecification.

OrderExpression

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/QuerySpecification.cs:155 · Level 0 · record (sealed)

  • What it is: one ordering key of a QuerySpecification<TEntity, TIdentifierType>: a key selector plus a direction flag.
  • Depends on: nothing first-party. System.Linq.Expressions (LambdaExpression).
  • Concept introduced, why the key selector is untyped. The declaration is public sealed record OrderExpression(LambdaExpression KeySelector, bool Descending) (QuerySpecification.cs:155). It holds a bare LambdaExpression, not an Expression<Func<TEntity, TKey>>, because a specification may order by a string key then an int key then a DateTime key, and those are three different closed generic types that cannot share one List<T>. Erasing the key type is what lets the ordering list be homogeneous; the repository-side evaluator binds each selector back to its concrete key type by reflection when it builds the OrderBy/ThenBy chain (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/SpecificationEvaluator.cs:158-159, which calls MakeGenericMethod(typeof(TEntity), keySelector.ReturnType) and invokes the resulting Queryable method). [Rubric §15, Best Practices & Code Quality] (assesses whether a design choice that costs type safety is deliberate and documented): the doc comment on the parameter (:145-148) states exactly this trade.
  • Walkthrough: two positional members, both from the record declaration.
    • KeySelector (:145-148), the lambda, added by the protected builder QuerySpecification.AddOrderBy (QuerySpecification.cs:99).
    • Descending (:149), whether this key sorts descending. The evaluator turns the first entry into OrderBy/OrderByDescending and every later one into ThenBy/ThenByDescending: the loop passes isFirst: i == 0 (SpecificationEvaluator.cs:123-128) and a tuple switch picks the method name from the (isFirst, descending) pair (SpecificationEvaluator.cs:150-155). The remarks (:140-144) explain why it is a top-level type rather than a member nested inside the generic specification: a nested type of a generic class is a different type per closed generic, which would stop the evaluator from handling an ordering list generically.
  • Where it's used: held in QuerySpecification's private _orderBy list and exposed as IReadOnlyList<OrderExpression> OrderBy (QuerySpecification.cs:48, :54); consumed by SpecificationEvaluator.ApplyOrdering (SpecificationEvaluator.cs:115-129).

ParameterReplacer

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/ParameterReplacer.cs:24 · Level 0 · class (internal, sealed)

  • What it is: an ExpressionVisitor that rebinds every occurrence of one ParameterExpression onto another, so two independently authored lambdas can be merged into a single lambda body. It is the composition primitive the whole specification family is built on.
  • Depends on: nothing first-party. System.Linq.Expressions (ExpressionVisitor, ParameterExpression).
  • Concept introduced, expression-tree rebinding via a visitor. [Rubric §8, Data Architecture] assesses whether query predicates reach the database rather than filtering in memory after a full load. Two independently built lambdas each own their own ParameterExpression (their x => variable), and a ParameterExpression is compared by reference, so you cannot merge two bodies just by giving the parameters the same name: you must physically visit one body and swap its parameter node for the other's. The class doc (ParameterReplacer.cs:8-16) states why substitution is chosen over the obvious alternative, Expression.Invoke(spec.Criteria, parameter): an InvocationExpression survives into the query tree, and several LINQ providers (Cosmos among them) refuse to translate one, so an ANDed specification failed on exactly the engines the framework is meant to be portable across. Substitution produces a tree indistinguishable from a hand-written predicate, so it translates everywhere.
  • Walkthrough: a primary-constructor sealed class taking (ParameterExpression from, ParameterExpression to) (:24) with one static entry point and one override.
    • public static Expression Replace(Expression body, ParameterExpression from, ParameterExpression to) (:34-41): null-guards all three arguments (:36-38), then short-circuits when from and to are already the same instance (ReferenceEquals, :40) so a no-op rebind allocates no visitor at all, and otherwise walks the body with a fresh visitor.
    • protected override Expression VisitParameter(ParameterExpression node) => node == from ? to : base.VisitParameter(node) (:44-45), the entire rewrite: when the visitor reaches the from parameter it returns to; every other node is left to the base visitor.
  • Why it's built this way: it is internal by design (the remarks say so at :18-23) because it is an implementation detail of specification composition, not part of the framework's public surface. MMCA.Common.Application sees it through InternalsVisibleTo (MMCA.Common/Source/Core/MMCA.Common.Domain/MMCA.Common.Domain.csproj:11, whose comment at :7-10 records the reason), which is what lets the Application-layer cross-source builder share this one visitor instead of carrying a private copy of it.
  • Where it's used: SpecificationComposer.Combine (MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:213), which is the path every AndSpecification and OrSpecification takes; and CrossSourceSpecification.BuildCriteria (MMCA.Common/Source/Core/MMCA.Common.Application/Specifications/CrossSourceSpecification.cs:92), which rebinds an optional local predicate onto the foreign-key selector's parameter before ANDing the two bodies.

ISpecification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Interfaces · MMCA.Common/Source/Core/MMCA.Common.Domain/Interfaces/ISpecification.cs:12 · Level 1 · interface

  • What it is: the Specification pattern interface: an encapsulated, reusable predicate that exposes both an EF-translatable expression tree (Criteria) and an in-memory evaluation path (IsSatisfiedBy).
  • Depends on: IBaseEntity<TIdentifierType> (the TEntity constraint, ISpecification.cs:13); System.Linq.Expressions (BCL).
  • Concept introduced, the Specification pattern. [Rubric §4, DDD] assesses whether business rules are modelled as first-class, named domain concepts rather than scattered conditionals; here a query criterion is a domain object. [Rubric §3, Clean Architecture] assesses whether the domain expresses rules while infrastructure translates them: Criteria is a pure expression tree the domain owns, and EF Core (an outer layer) is what turns it into SQL. A specification is a named, composable query criterion: instead of scattering Where(e => e.CreatedBy == userId) throughout the codebase, you write new OwnedByUserSpecification<...>(userId) once and reuse it. The doc comment (ISpecification.cs:5-8) lists the three use sites: authorization filtering, query scoping, and domain validation.
  • Walkthrough: two members, both constrained where TEntity : IBaseEntity<TIdentifierType> and where TIdentifierType : notnull (ISpecification.cs:13-14):
    • Expression<Func<TEntity, bool>> Criteria { get; } (ISpecification.cs:17), the expression tree EF Core translates to SQL via LINQ-to-DB. It is an expression, not a compiled Func, precisely so EF can inspect and translate it.
    • bool IsSatisfiedBy(TEntity entity) (ISpecification.cs:22), the compiled in-memory predicate, for unit-testing business rules or evaluating a rule against an already-materialized entity without a database. Both members on the same type is the key insight: one specification works equally against EF and in-memory collections, eliminating duplicate filter logic. [Rubric §14, Testability] (business rules become testable without infrastructure).
  • Where it's used: implemented by the abstract base Specification<TEntity, TIdentifierType> (next section), which is what the composites and every module-specific specification derive from (e.g. ADC's PublicSessionStatusSpecification, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/Specifications/PublicSessionStatusSpecification.cs:21); taken directly as the parameter type of the combinators (AndSpecification, OrSpecification, NotSpecification), of the fluent SpecificationExtensions, and of the optional specification argument on every scoped read method of IEntityQueryService<TEntity, TEntityDTO, TIdentifierType> (for example MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityQueryService.cs:40), and of the repository's specification-driven reads (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:599).

Specification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:15 · Level 2 · class (abstract)

  • What it is: the abstract base for the Specification pattern: subclasses supply an Expression<Func<TEntity, bool>> (Criteria, usable in EF Where clauses) and inherit an in-memory IsSatisfiedBy shortcut backed by a lazy-compiled, cached delegate.
  • Depends on: ISpecification<TEntity, TIdentifierType> (the contract it implements, Specification.cs:16), IBaseEntity<TIdentifierType> (the TEntity constraint, Specification.cs:17); System.Linq.Expressions (BCL).
  • Concept reinforced, the Specification pattern with expression trees. [Rubric §2, Design Patterns] assesses whether a pattern solves a real problem rather than being pattern theater; here specifications solve authorization scoping and reusable query predicates without leaking logic into repositories. [Rubric §4, DDD] (domain logic as reusable, composable predicates rather than scattered ifs). The pattern is dual-purpose: because Criteria is an expression tree (not a compiled delegate), EF Core can translate it to SQL, so Where(spec.Criteria) becomes a WHERE clause in the database; for in-memory use, IsSatisfiedBy compiles the same expression once and caches the result. One object, two evaluation modes, zero duplicate logic. The class doc states the dual purpose outright (Specification.cs:6-12).
  • Walkthrough
    • protected Specification() { } (Specification.cs:20), a do-nothing protected constructor so only subclasses (and the composites below) can construct one.
    • public abstract Expression<Func<TEntity, bool>> Criteria { get; } (Specification.cs:23), subclasses provide the expression tree; this is the single piece of state a concrete specification must define.
    • private Func<TEntity, bool>? _compiled (Specification.cs:27), the lazily-compiled delegate, cached to avoid recompiling the expression tree on every IsSatisfiedBy call (expression compilation is expensive; the comment at :25-26 says so).
    • public virtual bool IsSatisfiedBy(TEntity entity) (Specification.cs:30): _compiled ??= Criteria.Compile(); then return _compiled(entity); (Specification.cs:32-33). First call compiles; subsequent calls reuse the delegate. It is virtual, so a subclass could override it, though none in the workspace does.
  • Why it's built this way: placing Specification in MMCA.Common.Domain (not Infrastructure) keeps query business rules in the domain layer, where they are testable without an EF context or a database, and the domain stays free of any EF reference (the expression tree is plain BCL). The per-instance compile cache pays off for a specification instance that is reused, which the combinators below match: they cache their composed Criteria per instance too.
  • Where it's used: base class for InlineSpecification, the composites AndSpecification / OrSpecification / NotSpecification, the read-shape base QuerySpecification, the ownership filter OwnedByUserSpecification, and every module-specific access-control specification. It is also the declared return type of ADC's specification-building query handlers (for example MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionsController.cs:54-55, where the handler contracts are Result<Specification<Session, SessionIdentifierType>>). Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/SpecificationTests.cs:42.

DomainEventDispatcher

MMCA.Common.Application · MMCA.Common.Application.Services.Events · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/DomainEventDispatcher.cs:23 · Level 3 · class (public sealed)

  • What it is: the in-process implementation of IDomainEventDispatcher. It dispatches each event to every registered IDomainEventHandler<T> and, if the event also implements IIntegrationEvent, to every registered IIntegrationEventHandler<T> after running the event through the upcaster chain. It uses compiled expression-tree delegates cached per (event type, handler interface) to eliminate per-dispatch reflection.
  • Depends on: IDomainEvent, IDomainEventDispatcher, IDomainEventHandler<in TDomainEvent>, IIntegrationEvent, IIntegrationEventHandler<in TIntegrationEvent>, IEventUpcasterRegistry; externally IServiceProvider, System.Linq.Expressions, System.Collections.Concurrent, and ILogger<T>.
  • Concept introduced, compiled expression-tree delegates for handler dispatch. [Rubric §12, Performance & Scalability] (this is the hot post-SaveChanges path, so reflection cost compounds with every event on a busy request) and [Rubric §6, CQRS & Event-Driven] (events fan out to all registered handlers reliably). The problem: IServiceProvider.GetServices(closedHandlerType) (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/DomainEventDispatcher.cs:113) returns object instances, so calling the generic HandleAsync on them would otherwise require reflection on every dispatch. The solution: on first encounter of a (eventType, handlerInterfaceType) pair, BuildInvoker (DomainEventDispatcher.cs:136) uses Expression.Lambda to compile a Func<object, object, CancellationToken, Task> that casts the object arguments to their concrete types and calls HandleAsync directly (DomainEventDispatcher.cs:142-155). Subsequent dispatches of the same pair reuse the cached delegate, with zero reflection.
  • Concept introduced, where upcasting happens on the in-process path. The class doc (DomainEventDispatcher.cs:15-21) states the split precisely: the integration branch runs the event through IEventUpcasterRegistry first, so a retired contract reaches the handlers written against its successor (ADR-090). That also covers outbox rows written before an upgrade, which deserialize back into the old type. The IDomainEventHandler<T> branch is deliberately left untouched, because intra-module handlers keep receiving the original type and the original instance. [Rubric §9, API & Contract Design]: only the cross-boundary contract needs version tolerance; an in-module event has no independent deployment to be out of step with. The registry that performs the walk is EventUpcasterRegistry, the next section.
  • Walkthrough
    • _serviceProvider (DomainEventDispatcher.cs:25), null-checked in the field initializer.
    • _upcasterRegistry (DomainEventDispatcher.cs:32-33), a Lazy<IEventUpcasterRegistry?> over serviceProvider.GetService, resolved on first use and cached. GetService rather than GetRequiredService is deliberate and documented (DomainEventDispatcher.cs:27-31): this dispatcher is constructed directly in tests and in bare providers that never called AddApplication(), and no registry simply means no upcasting rather than a startup crash.
    • _isService (DomainEventDispatcher.cs:39-40), a Lazy<IServiceProviderIsService?> resolved the same way, and _handlerPresence (DomainEventDispatcher.cs:47), a per-instance ConcurrentDictionary<Type, bool>. The cache is deliberately not static, because two containers (two hosts, or two test fixtures) can register different handler sets (DomainEventDispatcher.cs:42-46).
    • HasDomainEventHandlers(Type eventType) (DomainEventDispatcher.cs:98-106), public but not on the interface, answers whether the container registers an IDomainEventHandler<> closed over exactly that type, through IServiceProviderIsService.IsService, cached per type (:102-105). It is conservative: a provider that cannot answer yields true (the != false at :104), and the remarks (:90-95) note that an open generic registration counts as present.
    • DispatchCache (DomainEventDispatcher.cs:55-57), a static ConcurrentDictionary keyed by (Type EventType, Type HandlerInterface) whose value is the tuple (Type ClosedHandlerType, Func<object, object, CancellationToken, Task> Invoker). Caching the closed handler type alongside the invoker keeps Type.MakeGenericType off the per-dispatch path (doc comment, DomainEventDispatcher.cs:49-54). Being static, the warmed cache is shared process-wide, and ConcurrentDictionary makes that thread-safe.
    • DispatchAsync (DomainEventDispatcher.cs:60) null-guards the batch (DomainEventDispatcher.cs:62), then per event always dispatches to IDomainEventHandler<> (DomainEventDispatcher.cs:69) and dispatches to IIntegrationEventHandler<> only when the event is also an IIntegrationEvent (DomainEventDispatcher.cs:74-79). The upcast happens on that branch: _upcasterRegistry.Value?.UpcastToTerminal(integrationEvent) ?? integrationEvent (DomainEventDispatcher.cs:76), and the terminal event's runtime type is what selects the handler set (DomainEventDispatcher.cs:78).
    • DispatchToHandlersAsync (DomainEventDispatcher.cs:108) GetOrAdds the cached (closedHandlerType, invoker) pair with a static factory (DomainEventDispatcher.cs:110-112, static so the lambda allocates no closure), resolves all handlers (DomainEventDispatcher.cs:113), and awaits each through the invoker (DomainEventDispatcher.cs:123). A null resolved handler is logged as a likely DI misconfiguration and skipped rather than throwing (DomainEventDispatcher.cs:117-121).
    • BuildInvoker (DomainEventDispatcher.cs:136) closes the open handler type (DomainEventDispatcher.cs:138), finds HandleAsync on it and throws a named InvalidOperationException if it is missing (DomainEventDispatcher.cs:139-140), builds ((IHandler<TEvent>)handler).HandleAsync((TEvent)event, ct) as an expression (DomainEventDispatcher.cs:142-152), and Compile()s it (DomainEventDispatcher.cs:154-155).
  • Why it's built this way: at-least-once domain-event delivery (ADR-003) requires the dispatcher to run after each SaveChangesAsync, so with many events per request the reflection cost would compound; the expression-tree cache makes dispatch near zero-cost after warm-up. Routing domain and integration events through one dispatcher rather than two keeps the in-process path uniform, which is precisely what lets InProcessMessageBus be a two-line adapter.
  • Where it's used: registered as the singleton IDomainEventDispatcher (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:41, beside the IEventUpcasterRegistry registration at DependencyInjection.cs:47). Its callers take the IDomainEventDispatcher interface: DomainEventSaveChangesInterceptor (constructor at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Interceptors/DomainEventSaveChangesInterceptor.cs:59) additionally type-tests for the concrete DomainEventDispatcher in NeedsOutboxRow and calls HasDomainEventHandlers, so a local (non-integration) event that no handler in this host handles gets no outbox row, while any other IDomainEventDispatcher keeps a row for every local event (DomainEventSaveChangesInterceptor.cs:332-335, doc at :309-316). It then hands the dispatcher to the internal InProcessDispatch loop after the outbox rows are written (:399 for the unbacked path, :405-406 for the outbox-backed path), and that loop calls DispatchAsync one event at a time (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/InProcessDispatch.cs:60, :100); the background OutboxProcessor resolves it per row and re-dispatches a persisted domain event (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Outbox/Processing/OutboxProcessor.cs:945-946); InProcessMessageBus forwards to it directly (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessMessageBus.cs:24, :31), and InProcessEventBus takes it as a constructor dependency (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/InProcessEventBus.cs:53). Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Events/DomainEventDispatcherTests.cs:11.

EventUpcasterRegistry

MMCA.Common.Application · MMCA.Common.Application.Services.Events · MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/EventUpcasterRegistry.cs:30 · Level 3 · class (public, sealed)

  • What it is: the default IEventUpcasterRegistry. It indexes every registered IEventUpcaster by the contract it consumes, precomputes where each upcast chain ends, and walks an incoming integration event forward to that terminal contract while keeping the envelope the producer stamped.
  • Depends on: IEventUpcasterRegistry (the interface it implements), IEventUpcaster, IIntegrationEvent, IDomainEvent (only for the nameof of the two envelope properties); System.Collections.Concurrent (ConcurrentDictionary) and System.Reflection (PropertyInfo) from the BCL.
  • Concept introduced, upcasting a retired event contract. [Rubric §6, CQRS & Event-Driven] assesses how well the event model handles change over time, and [Rubric §7, Microservices Readiness] assesses whether producers and consumers can deploy independently. Both meet here. Once an integration event has been published, its shape is a contract: a producer that has moved to FooV2 cannot assume every consumer redeployed at the same moment, and a queue can still hold Foo messages written before the change. Upcasting resolves that without a flag day. An author registers a small mapper that converts Foo into FooV2 (services.AddEventUpcaster<Foo, FooV2, FooUpcaster>(), MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Extensibility.cs:81-88), and this registry converts on the way in so that exactly one handler shape exists in the codebase, the newest one. Registrations compose: V1 to V2 plus V2 to V3 delivers a V1 message to the V3 handler (DependencyInjection.Extensibility.cs:69). [Rubric §15, Best Practices & Code Quality] covers the failure model: a bad registration graph is a programming error, so it throws at construction naming the offenders instead of returning a Result; the class remarks (:14-20) call that the permission-registry precedent, and note that because the graph is static once DI is built, terminal types are resolved once here rather than per message.
  • Walkthrough
    • State. EnvelopeProperties (static ConcurrentDictionary<Type, (PropertyInfo? MessageId, PropertyInfo? DateOccurred)>, :36) caches the two writable envelope handles per upcast target type, so a chain pays the reflection lookup once per contract for the life of the process. _bySourceType (Dictionary<Type, IEventUpcaster>, :38) is the index the walk follows, and _terminalTypes (Dictionary<Type, Type>, :39) is the precomputed answer to "where does this chain end".
    • Constructor (:50-82). After ArgumentNullException.ThrowIfNull(upcasters) (:52) it makes one pass over the registrations, collecting all offenders instead of failing on the first: an upcaster whose SourceType == TargetType is rejected as mapping a type onto itself (:59-63), a second upcaster claiming an already-claimed source is rejected as a duplicate naming both contenders (:65-69), and anything else is indexed (:71). If the offender list is non-empty it throws one InvalidOperationException joining every message and restating the rule, "exactly one upcaster may claim a source contract, and it must produce a different one" (:74-79). Only then is BuildTerminalTypes run (:81), so cycle detection sees an already-validated graph.
    • BuildTerminalTypes (:133-161) walks each source forward, carrying a visited set (:139) and a chain list for the error message (:140). Each hop advances by the upcaster's TargetType (:145); a type that fails to enter visited means the ladder came back on itself, and the throw renders the whole chain as A -> B -> C -> A (:148-154). The doc (:125-129) explains why a repeat is unambiguously a cycle rather than a diamond: the constructor already rejected duplicate sources, so the graph is functional (one outgoing edge per node). The final type reached is stored as that source's terminal (:157).
    • HasUpcasterFor(Type) (:85-90) is a plain containment check on _bySourceType, and ResolveTerminalType(Type) (:93-98) is a dictionary read that falls back to the type itself (:97), so an unregistered contract is its own terminal. That identity behavior is what lets the rest of the framework depend on the registry unconditionally.
    • UpcastToTerminal(IIntegrationEvent) (:101-123) is the hot path. It walks while a source has an upcaster (:110), rejects a null return with an InvalidOperationException naming the offending upcaster (:112-114), stamps the envelope (:116), and then advances currentType by the upcaster's declared TargetType, not the runtime type of what was returned (:119). The comment (:108-109) says why that matters: the constructor's acyclicity check was computed over declared types, so following declared types is what bounds this loop. With no registration at all, the loop never runs and the input instance is returned unchanged (:122).
    • PreserveEnvelope (:169-179) is the correctness detail. It pulls the cached MessageId and DateOccurred handles for the produced type (:171-175, keyed on target.GetType()), then copies both values from the pre-hop instance onto the new one (:177-178). Writable (:181-182) is the filter that caches a handle only when CanWrite is true, so a target that does not expose the property simply gets nothing written rather than throwing. Both properties are init-only on BaseDomainEvent (MMCA.Common/Source/Core/MMCA.Common.Domain/DomainEvents/BaseDomainEvent.cs:28 and :35), which reflection can still set.
    • Describe (:184, :186) renders a type or an upcaster instance as its FullName, which is what makes every one of the exception messages above name real types.
  • Why it's built this way: ADR-090 records the registration model, and the AddEventUpcaster remarks restate the policy it implements: a breaking event-shape change is a NEW event type plus a consumer-side upcaster (DependencyInjection.Extensibility.cs:57-58). Envelope preservation is deliberately the registry's job rather than the upcaster author's (EventUpcasterRegistry.cs:21-28 remarks): an upcaster maps payload fields only, and consumer-side inbox deduplication is keyed on the MessageId the producer published (ADR-021), so leaving the copy to each author would make dedup depend on every author remembering. Making it automatic also makes it idempotent: an author who does copy the envelope just gets the same values written twice, which the test at MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Events/EventUpcasterRegistryTests.cs:170 pins.
  • Where it's used: registered unconditionally as a singleton by AddApplication (services.TryAddSingleton<IEventUpcasterRegistry, EventUpcasterRegistry>(), MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:47), and populated by each AddEventUpcaster<TSource, TTarget, TUpcaster>() call, which appends the upcaster through TryAddEnumerable (DependencyInjection.Extensibility.cs:81-88, the descriptor at :86). Both delivery paths consume it: the in-process branch of DomainEventDispatcher (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Events/DomainEventDispatcher.cs:76, resolved through a Lazy<IEventUpcasterRegistry?> at :32-33 so a host without one still works) and the broker-side UpcastingIntegrationEventConsumer<TEvent> (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/UpcastingIntegrationEventConsumer.cs:75 for the probe and :79 for the walk). EventUpcasterStartupValidator exists purely to force construction at host start (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/EventUpcasterStartupValidator.cs:27 calls ResolveTerminalType for that side effect), so a broken graph fails the host rather than the first message. Behavior is pinned by EventUpcasterRegistryTests (identity at :88 and :187, chain walking at :116 and :130, envelope preservation at :153, and one test per constructor rejection at :199, :211, :223).
  • Caveats / not-in-source: the walk trusts declared types. An upcaster that returns an instance whose runtime type is not its declared TargetType still advances the walk by the declared type, and the envelope stamp is looked up by the runtime type, so the two can disagree; nothing in this class verifies the returned instance's type. Envelope stamping is also silently a no-op for a target that exposes no writable MessageId/DateOccurred (Writable, :181-182).

InlineSpecification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:45 · Level 3 · class (sealed)

  • What it is: a specification built from an already-composed Criteria expression, rather than from a fixed, hand-written specification subclass. It lets code that constructs a predicate dynamically (notably the cross-source filter built by CrossSourceSpecification, below) hand that expression back as a first-class Specification without declaring a one-off class.
  • Depends on: Specification<TEntity, TIdentifierType> (base class), ISpecification<TEntity, TIdentifierType> (via the base), IBaseEntity<TIdentifierType> (the TEntity constraint); System.Linq.Expressions (BCL).
  • Concept reinforced, a wrapper specification. The composites (AndSpecification and siblings) build new trees from existing specs; InlineSpecification instead adopts a tree someone else built. This is the small extension point that lets a dynamic, runtime-assembled predicate participate in the same Where(spec.Criteria) / IsSatisfiedBy machinery every other specification uses.
  • Walkthrough: a one-member sealed class with a primary constructor (Specification.cs:45-53):
    • InlineSpecification(Expression<Func<TEntity, bool>> criteria) (Specification.cs:45), the primary-constructor parameter is the pre-built criteria. Its doc comment (Specification.cs:44) states the caller's obligation: the expression must be EF-translatable to be usable in a DB query.
    • public override Expression<Func<TEntity, bool>> Criteria { get; } = criteria ?? throw new ArgumentNullException(nameof(criteria)); (Specification.cs:51-52), the inherited abstract Criteria is satisfied by a get-only auto-property initialized once (and null-guarded) from the constructor argument; IsSatisfiedBy is inherited unchanged from the base, so the lazy-compiled in-memory path works too.
  • Why it's built this way: without it, every helper that assembles a predicate at runtime would have to emit a bespoke Specification subclass per call site; a single sealed wrapper keeps that machinery to one type. It lives in MMCA.Common.Domain alongside the base and composites so the whole Specification family stays in the domain layer, while the Application layer builds on top of it (ADR-018's polyglot model is what makes that composition necessary).
  • Where it's used: returned by CrossSourceSpecification.BuildAsync to wrap the localPredicate AND principalKeys.Contains(fk) expression it assembles (MMCA.Common/Source/Core/MMCA.Common.Application/Specifications/CrossSourceSpecification.cs:66-67); and, across ADC Conference, by every filter handler that resolves ids first (over gRPC or from a sibling source) and then wraps the resulting ids.Contains(x.Id) predicate, for example GetSessionsBySpeakerFilterHandler (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/GetSessionsBySpeakerFilter/GetSessionsBySpeakerFilterHandler.cs:43), GetSpeakersByEventFilterHandler (.../Speakers/UseCases/GetSpeakersByEventFilter/GetSpeakersByEventFilterHandler.cs:53), and GetPublicSpeakerFilterHandler (.../Speakers/UseCases/GetPublicSpeakerFilter/GetPublicSpeakerFilterHandler.cs:31); and by PublicConferenceVisibility for its event-scope id list (.../Common/PublicConferenceVisibility.cs:149).

QuerySpecification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/QuerySpecification.cs:43 · Level 3 · class (abstract)

  • What it is: a Specification that carries the rest of a read's shape alongside its predicate: eager-load paths, ordering, paging, tracking, and whether soft-deleted rows are in scope. A repository can then serve a whole query from one object (ListAsync(spec)) instead of the caller threading five loose arguments through every layer.
  • Depends on: Specification<TEntity, TIdentifierType> (base class, QuerySpecification.cs:44), OrderExpression (the ordering list), IBaseEntity<TIdentifierType> (the TEntity constraint); System.Linq.Expressions (BCL).
  • Concept introduced, the specification as the whole read, not just the predicate. [Rubric §4, DDD] and [Rubric §5, Vertical Slice] both apply: a named class such as RecentOpenTicketsSpecification encodes the filter, the includes, the ordering and the page in one domain object that the application layer passes around as a value, instead of a handler assembling five arguments at every call site. The class doc carries the canonical example (QuerySpecification.cs:15-28). [Rubric §11, Security] covers the soft-delete opt-in: bringing deleted rows into scope drops the named SoftDelete filter and only that one, so the tenant filter stays in force and a specification asking for deleted rows can never reach another tenant's data (:74-82, enforced repository-side at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:579-581).
  • Walkthrough: state is exposed read-only and assembled through protected builders a derived specification calls from its constructor.
    • Backing fields _orderBy and _includePaths (:43-44) with the read-only projections IReadOnlyList<OrderExpression> OrderBy (:54) and IReadOnlyList<string> IncludePaths (:60), so a caller can read the shape but not mutate it (pinned by QuerySpecificationTests.cs:128).
    • int? Skip / int? Take (:63, :66), null when the specification does not page.
    • bool AsTracking (:72), defaulting to false: the doc states the rule, a specification-driven read is a read.
    • bool IgnoreQueryFilters (:82), defaulting to false, the soft-delete opt-in described above.
    • protected void AddOrderBy<TKey>(Expression<Func<TEntity, TKey>> keySelector, bool descending = false) (:90-95): null-guards the selector and appends an OrderExpression (:94). Call order is application order.
    • protected void AddInclude(string path) (:102-109): ignores blank paths (:104-105) and refuses to add the same path twice, compared with StringComparer.Ordinal (:107-108).
    • protected void ApplyPaging(int skip, int take) (:117-121): both values are floored at zero (:119-120), so a negative offset or size degrades to "from the start" / "no rows" instead of throwing inside the provider.
    • protected void WithTracking() (:127) and protected void WithSoftDeleted() (:133), the two opt-ins, each one line.
  • Why it's built this way: the base chain is deliberately QuerySpecification -> Specification (:29-34), because the SpecificationsDoNotNavigateToOtherEntities fitness rule keys on that base-type prefix and on a property literally named Criteria, so a query specification is analyzed by exactly the same rule as a plain one. That keeps the richer shape from becoming an escape hatch around the cross-source convention ([Rubric §34, Architecture Governance & Documentation]: the convention is machine-checked, not just written down).
  • Where it's used: read by SpecificationEvaluator, which pattern-matches a plain ISpecification against this type (SpecificationEvaluator.cs:56) and, when it matches, applies the includes (:51), the ordering chain (:52) and the Skip/Take window (:54-58); aggregate reads pass applyShape: false so a count never joins in includes or pages (:29-34, with the call sites at EFReadRepository.cs:454 and :516). The tracking and soft-delete flags are consumed one level up, in EFReadRepository.BaseQueryFor (EFReadRepository.cs:573-582), which chooses Table vs TableNoTracking (:443) and drops the named soft-delete filter (:445-447). Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/QuerySpecificationTests.cs:14, including the defaults (:55) and the fact that it still composes like any other specification (:68, :138).

SpecificationComposer

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:150 · Level 4 · class (internal, static)

  • What it is: the shared body of the boolean composers. Two generic methods that merge two criteria lambdas into one, or negate a single one, without ever emitting an InvocationExpression, plus a guard (RejectShaped) that refuses a shaped query specification before any composition happens.
  • Depends on: ISpecification<TEntity, TIdentifierType> (its arguments), ParameterReplacer (the rebind), IBaseEntity<TIdentifierType> (the TEntity constraint); System.Linq.Expressions (BCL).
  • Concept introduced, one composition algorithm instead of three copies. [Rubric §15, Best Practices & Code Quality] assesses whether a rule with a subtle correctness argument is written once. And, Or and Not differ by exactly one expression node, so a per-combinator copy of the parameter-rebinding logic would be three places the Expression.Invoke mistake could come back. Collapsing them into Combine (parameterized by the binary-operator factory) and Negate leaves one implementation to reason about and one to test. The type doc (Specification.cs:145-149) names the invariant it guarantees: the composed tree contains no InvocationExpression.
  • Walkthrough
    • RejectShaped<TEntity, TIdentifierType>(spec, parameterName) (Specification.cs:164-178): the composed specification is criteria-only, so a QuerySpecification carrying includes, ordering, paging, tracking or soft-delete scope would silently lose that shape. The guard throws an ArgumentException naming the offending parameter (:171-176) when the argument is a QuerySpecification and the private HasShape check (:181-189) finds a non-empty OrderBy or IncludePaths, a Skip or Take, AsTracking, or IgnoreQueryFilters. An unshaped query specification, or any other ISpecification, is returned unchanged. The message tells the caller to compose the predicates inside the query specification's own Criteria instead.
    • Combine<TEntity, TIdentifierType>(spec1, spec2, Func<Expression, Expression, BinaryExpression> combine) (Specification.cs:197-216): null-guards both specifications (:205-206), takes the left lambda's parameter as the one both sides will share (:210), rebinds the right body onto it with ParameterReplacer.Replace (:214), applies the caller's operator factory to the two bodies (:212-214), and re-wraps the result as Expression.Lambda<Func<TEntity, bool>>(body, parameter) (:216). The operator factory is how one method serves both Expression.AndAlso and Expression.OrElse.
    • Negate<TEntity, TIdentifierType>(spec) (Specification.cs:223-234): null-guards (:229), then wraps the inner body in Expression.Not while keeping the inner lambda's own parameter (:232-234). There is nothing to rebind with one operand, so no visitor runs at all.
  • Why it's built this way: internal and static, because it is a composition mechanism rather than a domain concept; the three public combinators are the vocabulary a caller sees. Every returned tree contains only nodes a LINQ provider can translate, which is the property the whole family depends on.
  • Where it's used: from the constructors and cached Criteria getters of AndSpecification (Specification.cs:87-88, :94-95), OrSpecification (:114-115, :120-121) and NotSpecification (:138, :143): each runs its argument(s) through RejectShaped once at construction. The no-Invoke guarantee is pinned directly by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/SpecificationTests.cs:251, :263, :273 and :281 (one per combinator plus a nested composition), and the single-parameter property by :294.

OwnedByUserSpecification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/OwnedByUserSpecification.cs:20 · Level 4 · class (sealed)

  • What it is: the framework's one reusable ownership filter. It restricts a query to the rows a single user created, using the CreatedBy audit field as the ownership marker, so a "my own records" read (an attendee seeing only the answers they submitted) is one specification instance rather than a hand-written Where per controller.
  • Depends on: Specification<TEntity, TIdentifierType> (base class, OwnedByUserSpecification.cs:21), AuditableBaseEntity<TIdentifierType> (the TEntity constraint, OwnedByUserSpecification.cs:22, which is what supplies CreatedBy), and the solution-wide UserIdentifierType alias (int, declared at MMCA.Common/Source/Core/MMCA.Common.Domain/GlobalUsings.IdentifierType.cs:1 and linked into every project, see the primer's identifier-alias convention); System.Linq.Expressions (BCL).
  • Concept introduced, row-level authorization as a query predicate. [Rubric §11, Security] assesses whether authorization is enforced where the data is fetched rather than after the fact: because this is a Criteria expression, the ownership test becomes part of the SQL WHERE clause, so rows the caller may not see are never materialized and cannot leak through a projection, a count, or a paging total. [Rubric §12, Performance & Scalability] is the same fact read the other way: filtering at the store means the page size bounds the owner's rows, not the whole table. The complementary half of the pattern lives at the call site: a caller holding a bypass role simply does not build the specification and passes null instead (the class doc spells that out, OwnedByUserSpecification.cs:6-11).
  • Walkthrough: a sealed primary-constructor subclass, OwnedByUserSpecification<TEntity, TIdentifierType>(UserIdentifierType userId) (OwnedByUserSpecification.cs:20):
    • public UserIdentifierType UserId { get; } = userId; (OwnedByUserSpecification.cs:26), the owning user's id kept as a readable property rather than a captured constructor parameter, so a caller (or a test) can assert what the specification is scoped to.
    • public override Expression<Func<TEntity, bool>> Criteria => e => e.CreatedBy == UserId; (OwnedByUserSpecification.cs:29-30), the whole rule: one equality node over the audit column. It is an expression-bodied property, so a fresh tree is built per get, and IsSatisfiedBy comes free from the base class's lazy-compiled path.
    • The generic constraint is deliberate. where TEntity : AuditableBaseEntity<TIdentifierType> (OwnedByUserSpecification.cs:22) pins the constraint to the concrete base class rather than the IAuditableEntity interface: the remarks (OwnedByUserSpecification.cs:12-16) explain that a member access declared on an interface is not guaranteed to map to the entity's audit column, and the criteria has to stay EF-translatable. CreatedBy itself is declared virtual with a private setter on the base (MMCA.Common/Source/Core/MMCA.Common.Domain/Entities/AuditableBaseEntity.cs:27) and is stamped by the infrastructure layer, never by the caller.
  • Why it's built this way: ownership is already recorded by the framework's audit-field convention (see the primer's soft-delete + audit section), so the cheapest correct ownership filter is a predicate over that existing column: no extra OwnerId property per entity, no per-module duplicate of the same Where. Keeping it in MMCA.Common.Domain next to the base and the combinators means it composes with them (NotSpecification inverts it, AndSpecification narrows it further) with no extra machinery.
  • Where it's used: ADC Conference's two question-answer controllers, each of which builds it for every non-organizer caller from a single overridden read hook, so all of that controller's read actions (list, paged, lookup, by-id) are scoped from one place and another attendee's answer is a 404 rather than a redacted record: SessionQuestionAnswersController (BR-9, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionQuestionAnswersController.cs:100-101) and EventQuestionAnswersController (BR-8, .../Controllers/EventQuestionAnswersController.cs:74-75). Both read the caller's role and id from ICurrentUserService and return null for an organizer. Behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/OwnedByUserSpecificationTests.cs:8, which asserts not only the in-memory outcome (:30, :38) but the shape of the expression (an Equal binary node whose left side is a MemberExpression for CreatedBy over the lambda parameter, OwnedByUserSpecificationTests.cs:55), which is exactly what keeps it translatable, plus the queryable-filtering case at :83.
  • Caveats / not-in-source: the read hook the two ADC controllers override is named GetExportSpecification() (SessionQuestionAnswersController.cs:111); its doc comment describes it as the framework's synchronous read hook applied to every read action. Whether that name still matches its breadth is a naming question the source does not resolve.

AndSpecification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:80 · Level 5 · class (sealed)

  • What it is: a composite combinator that ANDs two specifications into a new one whose Criteria is satisfied only when both children are. Its siblings OrSpecification and NotSpecification share the identical shape and differ only in the composer call they make, so this section teaches the mechanism once and those two cross-reference it.
  • Depends on: Specification<TEntity, TIdentifierType> (base class), ISpecification<TEntity, TIdentifierType> (the two constructor parameters, Specification.cs:81-82), SpecificationComposer (the merge), IBaseEntity<TIdentifierType> (the TEntity constraint); System.Linq.Expressions (BCL).
  • Concept introduced, composing by parameter substitution rather than invocation. [Rubric §8, Data Architecture] assesses whether query predicates reach the database rather than filtering in-memory after a full load, and [Rubric §7, Microservices Readiness] covers the engine-portability half. The remarks (Specification.cs:58-75) state the whole argument: the two criteria are merged by parameter substitution (see ParameterReplacer), the right-hand body is rebound onto the left-hand lambda's parameter, and the two bodies are joined with Expression.AndAlso, giving a tree indistinguishable from a hand-written predicate. It deliberately does not use Expression.Invoke: an InvocationExpression survives into the query tree, and while EF Core's relational providers can usually unwrap it, others (Cosmos in particular) throw at translation time, so an ANDed specification failed on exactly the engines the framework is meant to be portable across.
  • Walkthrough: a sealed primary-constructor subclass taking two ISpecifications (Specification.cs:80-82), with four members:
    • _spec1 and _spec2 (:88-89), private readonly fields initialized from the constructor parameters through SpecificationComposer.RejectShaped(spec1, nameof(spec1)), so a QuerySpecification carrying includes, ordering, paging, tracking or soft-delete scope throws an ArgumentException at construction instead of having that shape silently dropped (see SpecificationComposer).
    • private Expression<Func<TEntity, bool>>? _criteria (:90), the per-instance cache.
    • public override Expression<Func<TEntity, bool>> Criteria => _criteria ??= SpecificationComposer.Combine<TEntity, TIdentifierType>(_spec1, _spec2, Expression.AndAlso) (:93-95). The ??= is the second half of the remarks (:71-75): rebuilding the whole tree on every Criteria read would repeat that work at least once per request, so the composed expression is built once per instance. Each instance still owns its own cache, so two separately constructed composites never share a tree (SpecificationTests.cs:338).
  • Why it's built this way: combinators let query callers compose access rules without the query service knowing the predicate internals, and composing at the expression-tree level (not by combining compiled Funcs) preserves database translation throughout the composition. Keeping it sealed signals it is a leaf implementation, not meant for further subclassing.
  • Where it's used: it is the one combinator with production call sites, and all of them reach it through the fluent SpecificationExtensions.And rather than the constructor. ADC's SessionsController ANDs the public-session filter with the speaker-scoped filter when a SpeakerId filter is present (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionsController.cs:137-139, the composite then passed as the specification argument at :187) and SpeakersController does the same for its own public/filtered pair (.../Controllers/SpeakersController.cs:171-173); ADC's PublicConferenceVisibility ANDs the shared status allow-list with an id-list InlineSpecification when resolving eligible session ids (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Common/PublicConferenceVisibility.cs:148). Combinator behavior is pinned by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/SpecificationTests.cs:49 and by the composition cases in the same file (SpecificationTests.cs:310 for the build-once property, :355 for the semantics, :407 for the null-argument guard).

NotSpecification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:131 · Level 5 · class (sealed)

  • What it is: the negating composite combinator: it wraps a single specification and satisfies its Criteria when the child does not. Same shape as AndSpecification (read that section for the substitution-over-invocation argument); it just takes one child instead of two.
  • Depends on: same as AndSpecification, but its constructor takes a single ISpecification<TEntity, TIdentifierType> (Specification.cs:132).
  • Walkthrough: a _spec field (:138) initialized through SpecificationComposer.RejectShaped(spec, nameof(spec)), so a shaped QuerySpecification is refused at construction with an ArgumentException; a _criteria cache field (:139); and the getter Criteria => _criteria ??= SpecificationComposer.Negate<TEntity, TIdentifierType>(_spec) (:142-143). Negate wraps the inner body in Expression.Not and reuses the inner lambda's own parameter, so no rebinding is needed and no Expression.Invoke appears (doc comment, :124-128). sealed.
  • Where it's used: "exclude this set" predicates, composed with the other combinators and passed as the specification argument to the query service. No production call site in the workspace today; it is exercised by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/SpecificationTests.cs:99 and :110, nested inside a composition at SpecificationTests.cs:61, checked for invocation-freedom at SpecificationTests.cs:273, for the build-once property at :330, and wrapping the ownership filter at OwnedByUserSpecificationTests.cs:72.

OrSpecification<TEntity, TIdentifierType>

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/Specification.cs:106 · Level 5 · class (sealed)

  • What it is: the disjunctive composite combinator: it ORs two specifications so its Criteria is satisfied when either child is. Structurally identical to AndSpecification (read that section for the mechanism); it differs by one argument to the composer.
  • Depends on: identical to AndSpecification (Specification.cs:106-109).
  • Walkthrough: the _spec1 and _spec2 fields (:114-115), each initialized through SpecificationComposer.RejectShaped (a shaped QuerySpecification throws ArgumentException at construction), the _criteria cache field (:116) and the getter Criteria => _criteria ??= SpecificationComposer.Combine<TEntity, TIdentifierType>(_spec1, _spec2, Expression.OrElse) (:119-121), the And getter with Expression.OrElse (a short-circuiting logical OR) in place of Expression.AndAlso. sealed.
  • Where it's used: "admin or owner" access patterns where either condition grants access, composed with the other combinators and passed as the specification argument to the query service. No production call site in the workspace today; it is exercised by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/SpecificationTests.cs:74, by the invocation-freedom and build-once cases in SpecificationTests.cs:263 and :320, and by the allocation benchmark that composes And over Or (MMCA.Common/Tests/Performance/MMCA.Common.Benchmarks/SpecificationBenchmarks.cs:48-50).

SpecificationExtensions

MMCA.Common.Domain · MMCA.Common.Domain.Specifications · MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/SpecificationExtensions.cs:36 · Level 4 · class (public, static)

  • What it is: the fluent face of the three combinators. And, Or and Not as extension members on any ISpecification<TEntity, TIdentifierType>, so a composed predicate reads left to right instead of inside out.
  • Depends on: ISpecification<TEntity, TIdentifierType> (the receiver), AndSpecification / OrSpecification / NotSpecification (the return types), IBaseEntity<TIdentifierType> (the TEntity constraint).
  • Concept introduced, the C# extension(T) block. The whole class body is a single extension<TEntity, TIdentifierType>(ISpecification<TEntity, TIdentifierType> specification) block (SpecificationExtensions.cs:38-40) carrying its own generic constraints, with the three members declared inside it as ordinary instance-looking methods. This is the extension-member syntax the workspace uses throughout (see the primer's extension(T) note): the receiver is named once on the block rather than repeated as a this parameter on every method, and the constraints are stated once. [Rubric §15, Best Practices & Code Quality] (assesses idiomatic use of current language features) and [Rubric §15, Best Practices & Code Quality].
  • Walkthrough: three members, each a thin factory that null-guards both the receiver and the argument before constructing the corresponding combinator.
    • And(ISpecification<TEntity, TIdentifierType> other) returning AndSpecification<TEntity, TIdentifierType> (:48-54), guards at :50-51, construction at :53.
    • Or(ISpecification<TEntity, TIdentifierType> other) returning OrSpecification<TEntity, TIdentifierType> (:68-74).
    • Not() returning NotSpecification<TEntity, TIdentifierType> (:85-90). Note the return types are the concrete combinators, not ISpecification, so a fluent chain keeps composing without a cast.
  • Why it's built this way: the class doc (:5-29) contrasts the two spellings directly, nested constructors versus the fluent chain, and closes with the performance note that follows from the combinators' per-instance caching: hold on to the composed specification (a field, a local) rather than rebuilding it per request if the composition itself is on a hot path.
  • Where it's used: And is the spelling every production composition in the workspace uses. ADC's SessionsController writes publicSpecification.And(speakerResult.Value!) (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionsController.cs:139), SpeakersController writes publicSpecification.And(filterResult.Value!) (.../Controllers/SpeakersController.cs:173), and PublicConferenceVisibility chains .And(new InlineSpecification<Session, SessionIdentifierType>(...)) (.../Common/PublicConferenceVisibility.cs:149). All three guard the null case first, because the extension throws on a null receiver. Or and Not have no production call site today. The whole fluent surface is exercised by MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Specifications/SpecificationTests.cs:428, :438, :447, the left-to-right chain at :456, and the null guards at :466 and :476.

CrossSourceSpecification

MMCA.Common.Application · MMCA.Common.Application.Specifications · MMCA.Common/Source/Core/MMCA.Common.Application/Specifications/CrossSourceSpecification.cs:26 · Level 8 · class (public, static)

  • What it is: a static helper that builds a specification filtering a dependent entity by a condition on a cross-source principal it references by foreign key. Its single public method, BuildAsync, resolves the matching principal keys first (a scalar projection query against the principal's own data source) and returns an InlineSpecification whose criteria is the engine-portable localPredicate AND principalKeys.Contains(dependent.ForeignKey).
  • Depends on: InlineSpecification<TEntity, TIdentifierType> and Specification<TEntity, TIdentifierType> (the return type), ParameterReplacer (the shared rebind visitor, reached through InternalsVisibleTo), IUnitOfWork with GetReadRepository<,> / GetProjectedAsync (G07) to query the principal source, AuditableBaseEntity<TIdentifierType> (the TPrincipal constraint) and IBaseEntity<TIdentifierType> (the TDependent constraint); System.Linq.Expressions (BCL).
  • Concept introduced, cross-source filtering under polyglot persistence [Rubric §8, Data Architecture]. In a database-per-service (ADR-006) or polyglot (ADR-018) setup an entity and a related entity can live in different physical data sources (e.g. a Cosmos-stored Session referencing a SQL-Server Event). A query cannot join across physical sources, so a predicate that navigates, s => s.Event.IsPublished, is not translatable; on Cosmos the cross-source navigation is even degraded out of the model entirely by CrossDataSourceDegradeConvention. The engine-portable alternative is resolve-then-filter-by-FK: read the principal keys that satisfy the condition from the principal's own source, then filter the dependent by foreignKey IN (those keys), which every provider translates (SQL IN, Cosmos ARRAY_CONTAINS). The convention is enforced by the opt-in fitness rule ArchitectureRules.SpecificationsDoNotNavigateToOtherEntities (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Domain/ArchitectureRules.Specifications.cs:24), which ADC subclasses through SpecificationConventionTestsBase (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Domain/SpecificationConventionTests.cs:8). Note the rule analyzes only parameterless specifications, whose Criteria it can instantiate and inspect (ArchitectureRules.Specifications.cs:18-20).
  • Walkthrough
    • BuildAsync<TDependent, TDependentId, TPrincipal, TPrincipalId>(IUnitOfWork unitOfWork, Expression<Func<TPrincipal, bool>> principalPredicate, Expression<Func<TDependent, TPrincipalId>> dependentForeignKey, Expression<Func<TDependent, bool>>? localPredicate = null, CancellationToken = default) (CrossSourceSpecification.cs:43-68), four type parameters: the dependent plus its id, and the principal plus its id (which is also the dependent's FK type). Constraints require TPrincipal : AuditableBaseEntity<TPrincipalId> (:51), and the three reference arguments are null-guarded up front (:54-56).
    • Resolves keys: unitOfWork.GetReadRepository<TPrincipal, TPrincipalId>() (:58) then GetProjectedAsync(p => p.Id, principalPredicate, asTracking: false, cancellationToken) (:59-61), materialized once into a list (:64, comment at :63) so the predicate carries a stable collection EF can translate; the result is wrapped as an InlineSpecification (:66-67).
    • BuildCriteria (:70-97) reuses the FK selector's own parameter (:75) and builds Enumerable.Contains(keys, fk) via Expression.Call (:80-85). The keys argument is not the list as a constant: it is a property read on a private KeyCarrier<TPrincipalId> wrapped in a constant (:84), the shape a captured local has, so EF extracts the keys as a query parameter instead of inlining them as literals (the comment at :77-79). If a localPredicate is supplied it is rebound onto that same parameter via ParameterReplacer (:92) and ANDed with Expression.AndAlso (:93), deliberately not Expression.Invoke, so the combined predicate stays translatable on every provider. The comment there (:89-91) also records that the visitor is the one the Domain composers use, shared rather than duplicated here. The finished body is wrapped as a lambda over that parameter (:96).
  • Why it's built this way: it makes a module's storage engine a movable choice (ADR-018): a session-by-published-event filter written this way keeps working whether Session is in SQL Server, SQLite, or Cosmos, with no query rewrite. Returning an InlineSpecification means the result drops straight into the existing IEntityQueryService and read-repository specification argument.
  • Where it's used: two ADC Conference call sites, both resolving published Event ids and filtering Session.EventId IN (...) with the shared status allow-list PublicSessionStatusSpecification.StatusCriteria passed as the localPredicate (BR-49: status unset or Accepted, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/Specifications/PublicSessionStatusSpecification.cs:24): GetPublicSessionFilterHandler (.../Sessions/UseCases/GetPublicSessionFilter/GetPublicSessionFilterHandler.cs:29, with the localPredicate at :34), which supplies the specification for the public session reads, and PublicConferenceVisibility.GetVisibleSessionIdsAsync (.../Common/PublicConferenceVisibility.cs:57, the call at :63-64 and the same localPredicate at :68), which uses the identical criteria to resolve the visible session ids so a session hidden from the session list cannot stay reachable through a speaker or junction read (the comment at :61-62 says exactly that).
  • Caveats / not-in-source: the matching keys are materialized and carried in the predicate, so this fits small/bounded principal sets (the common "published events", "active tenants" shape). The class doc (CrossSourceSpecification.cs:17-24) states this explicitly, and adds that the key list reaches the database as a query parameter rather than inlined literals, because a literal list meant one SQL text, query plan and compiled-query cache entry per distinct key set (:20-23). That is pinned against the SQL Server provider by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Specifications/SqlServerQueryShapeTests.cs:35 (the keys must render as @ parameters inside the IN, never as IN (1, 2), at :41-42) and :46 (two different key sets of the same size render identical SQL). The SQL Server rendering still uses one parameter per key (:42), so an unbounded principal set yields a very long parameter list, and key sets of different sizes still render different SQL text; the behavior on the other providers is not determinable from that test, which renders SQL Server only (:13-17). It is also a point-in-time snapshot: the keys are read before the dependent query runs, so a principal that changes state in between is not reflected until the specification is rebuilt.

IEntityQueryService<TEntity, TEntityDTO, TIdentifierType>

MMCA.Common.Application · MMCA.Common.Application.Interfaces.Mapping · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityQueryService.cs:19 · Level 5 · interface (generic)

  • What it is: the central read-query contract of the framework: generic operations for GetAllAsync (with filter/sort/pagination/projection), GetAllForLookupAsync, GetEntityByIdAsync, GetByIdAsync, and ExistsAsync over any entity/DTO pair, plus two keyset reads, GetPageByCursorAsync (cursor paging) and GetChangesSinceAsync (the change feed). It is the read half of the application's CQRS split (the write half flows through command handlers).
  • Depends on: AuditableBaseEntity<TIdentifierType> (the TEntity constraint, IEntityQueryService.cs:20), IBaseDTO<TIdentifierType> (the TEntityDTO constraint, IEntityQueryService.cs:21), IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType> (the DTOMapper property), ISpecification<TEntity, TIdentifierType> (the optional scoping argument), PagedCollectionResult<T>, Result, BaseLookup<TIdentifierType>, KeysetPageRequest, KeysetCollectionResult<T>, EntityChange<TEntityDTO, TIdentifierType>; System.Linq.Expressions (BCL).
  • Concept introduced, the entity query service contract. [Rubric §5, Vertical Slice] assesses whether a feature's read logic is encapsulated in one place; here the API controller delegates to this service and never touches IQueryable directly. [Rubric §12, Performance & Scalability] assesses whether result sets are bounded; explicit pageNumber/pageSize parameters and a fields projection prevent returning unbounded rows or over-fetching columns. [Rubric §9, API & Contract Design] assesses whether one contract can serve varied response shapes without proliferating types, and the most distinctive design choice here answers exactly that: the read methods return Result<...<object>>. The interface doc (IEntityQueryService.cs:9-15) explains it: when no fields subset is requested the typed TEntityDTOs are returned as-is (no per-row shaping cost); when an explicit fields list is supplied, dynamically shaped objects carrying only the requested fields are returned. Both serialize to the same camelCase JSON, so one contract serves full-detail and sparse-field responses alike, without one DTO per projection.
  • Walkthrough: constraints where TEntity : AuditableBaseEntity<TIdentifierType>, where TEntityDTO : IBaseDTO<TIdentifierType>, where TIdentifierType : notnull (IEntityQueryService.cs:20-22):
    • IEntityDTOMapper<...> DTOMapper { get; } (IEntityQueryService.cs:25), exposes the mapper so callers can do manual entity-to-DTO mapping outside the pipeline when needed (e.g. a custom join result).
    • GetAllAsync(...) (IEntityQueryService.cs:37-43), the simple overload: navigate FKs and/or children (includeFKs/includeChildren), optionally scope by an ISpecification, optionally project fields, optionally track; returns Task<Result<PagedCollectionResult<object>>>.
    • GetAllAsync(...) (IEntityQueryService.cs:60-71), the full overload: adds filters (Dictionary<string, (string Operator, string Value)>, a dynamic filter map), sortColumn, sortDirection ("asc"/"desc"), pageNumber, pageSize. Callers pick the minimal overload for their use case.
    • GetAllForLookupAsync(string nameProperty, ...) (IEntityQueryService.cs:86-90), returns lightweight IReadOnlyCollection<BaseLookup<TIdentifierType>> id/name pairs for dropdowns, with an optional where expression. There is deliberately no ordering parameter: results are always ordered by the projected display name, and the remarks (IEntityQueryService.cs:81-85) state there is no ordering parameter because the repository's lookup read has no ordering hook. Not offering a parameter that could not be honored is the contract choice, [Rubric §9, API & Contract Design].
    • GetEntityByIdAsync(string idValue, ...) (IEntityQueryService.cs:104-112), returns the raw Result<TEntity> (the entity itself) for command handlers that need to mutate it; takes the id as a string plus an optional idField (defaulting to "Id") so non-Id lookups are possible.
    • GetByIdAsync(TIdentifierType id, ...) (IEntityQueryService.cs:126-133), returns a projected Result<object> (typed DTO, or shaped object when a field subset was requested) for read-only detail responses. On both single-row reads the specification parameter doc (IEntityQueryService.cs:99, :121) pins what a specification contributes: its criteria, soft-delete scope, includes and tracking apply exactly as on the list read, while its ordering and paging do not (a single row has nothing to order or page).
    • ExistsAsync(Expression<Func<TEntity, bool>> where, bool ignoreQueryFilters = false, ...) (IEntityQueryService.cs:142-145), a cheap existence check. Note it returns a bare Task<bool>, not a Result: absence is an answer, not a failure. ignoreQueryFilters bypasses the global query filters (soft-delete), which is how a uniqueness check can still see a soft-deleted row.
    • GetPageByCursorAsync(KeysetPageRequest request, ...) (IEntityQueryService.cs:159-162), one keyset ("seek") page of typed TEntityDTOs as Result<KeysetCollectionResult<TEntityDTO>>: the rows after the request's cursor, ordered by a single DTO-named sort column with Id as tie-break, plus the next page's cursor. The remarks (IEntityQueryService.cs:158) note that no includes, field projection or filter dictionary apply: only a specification scopes it.
    • GetChangesSinceAsync(DateTime? since, string? cursor, int pageSize, ...) (IEntityQueryService.cs:186-191), one page of the change feed as Result<KeysetCollectionResult<EntityChange<TEntityDTO, TIdentifierType>>>: every row whose LastModifiedOn is at or after since (soft-deleted rows included), ordered by (LastModifiedOn, Id) ascending, each an upsert carrying the DTO or a tombstone carrying no item. The remarks (IEntityQueryService.cs:180-185) give the client protocol: page with the same since until the next cursor is null, then keep the largest ChangedOn; the inclusive bound replays boundary rows, which are applied idempotently, and a row that left the scope without being deleted yields no tombstone. Both keyset members are plain abstract members with no default body (IEntityQueryService.cs:162, :191), so every implementation of the interface must serve them; their documented failures are validation failures only (an unknown sort column or a malformed cursor, IEntityQueryService.cs:156, :178). All six scoped reads take the interface ISpecification<TEntity, TIdentifierType>, not the abstract base class (:40, :63, :109, :130, :161, :190), so any implementation (including a hand-rolled one that does not derive from Specification) can scope a read.
  • Why it's built this way: a single generic read contract over every entity lets the generic controller base (G12) expose uniform list/detail/lookup/exists endpoints without per-entity query code, while the object return plus fields shaping keeps the wire payload caller-controlled without paying a shaping cost when no projection is asked for. Splitting GetEntityByIdAsync (raw entity) from GetByIdAsync (shaped DTO) cleanly separates the command-side need (an aggregate to mutate) from the query-side need (a projected response). ADR-034 records the trade-offs of the generic read layer; ADR-145 covers the opt-in cursor read and ADR-144 the delta (change-feed) read.
  • Where it's used: implemented by EntityQueryService<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:35), which takes INavigationMetadataProvider and IEntityQueryPipeline as constructor dependencies (:37-38) and delegates navigation classification and query execution to them, and implements both keyset reads as public virtual methods (EntityQueryService.cs:589, :630); consumed by every read endpoint through the generic controller base (G12), for example ADC's SessionsController, which passes its specification as the specification argument at MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionsController.cs:157 and :194.


⬅ Domain Building Blocks (Entities, Value Objects, Aggregates) • Index • Domain & Integration Events + Outbox Dual-Dispatch ➡