Onboarding guide
11. Navigation Metadata & Populators (EF-decoupled eager loading)
EF Core gives you .Include() for eager loading, and for a single SQL Server database that is the
right tool. But this codebase is a database-per-service modular monolith
(ADR-006): two related entities
can live in different physical data sources, different SQL databases, or a Cosmos container that
has no JOINs at all, and across that boundary EF's Include cannot produce a JOIN. The relationship
is real in the domain model, but the physical storage cannot satisfy it in one query. This chapter is
the framework's answer to that gap: a small, self-contained subsystem that decides which
navigations EF can load and which must be hand-loaded, then batch-loads the latter without leaking
EF or the physical split into the Application or Domain layers. It is the machinery behind
ADR-002 (navigation
populators), and it sits directly underneath the query pipeline taught in
Group 03.
The whole feature turns on one piece of metadata you author in the Domain layer and one piece the
framework computes at runtime. In the domain, a navigation property is tagged with
NavigationAttribute
(MMCA.Common/Source/Core/MMCA.Common.Domain/Attributes/NavigationAttribute.cs:10), a sealed
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)] marker
(NavigationAttribute.cs:9) carrying a single IsCollection init-only flag
(NavigationAttribute.cs:16) that says "this is a one-to-many child collection" versus "this is a
many-to-one FK reference". That attribute lives in MMCA.Common.Domain deliberately: the domain
entity declares what relationships it has with zero EF dependency ([Rubric §3, Clean Architecture], the inward dependency rule, so the domain stays persistence-ignorant). At runtime the
framework needs a richer, classified view of those navigations, which it carries in three
Application-layer types declared in one file: the NavigationType enum
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationMetadata.cs:6, values
ForeignKey and ChildCollection), the NavigationPropertyInfo record
(INavigationMetadata.cs:23, one navigation's property name, kind, declaring type, and unwrapped
target type), and the INavigationMetadata contract
(INavigationMetadata.cs:34) whose two read-only lists are the heart of the design:
SupportedIncludes (navigations EF can JOIN, because both ends share a data source,
INavigationMetadata.cs:37) and UnsupportedIncludes (navigations that need manual loading,
because the ends are split, INavigationMetadata.cs:40). Its mutable builder implementation is
NavigationMetadata
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/NavigationMetadata.cs:9), which backs
each list with a List<NavigationPropertyInfo> and exposes only internal AddSupported /
AddUnsupported / AddSupportedRange / AddUnsupportedRange mutators
(NavigationMetadata.cs:22-34), so nothing outside the framework assembly can rewrite a
classification after the fact.
That split is computed by NavigationMetadataProvider
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:20),
a sealed class whose only constructor dependency is IDataSourceService, registered behind the
INavigationMetadataProvider port
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/INavigationMetadataProvider.cs:9),
whose single member is BuildIncludes<TEntity>(bool includeFKs, bool includeChildren)
(INavigationMetadataProvider.cs:19). Given an entity type and the caller's
includeFKs/includeChildren choice, the implementation's BuildIncludes<TEntity>
(NavigationMetadataProvider.cs:31)
reflects over the entity's public instance properties, keeps the [Navigation]-tagged ones whose
IsCollection flag matches the requested kind (NavigationMetadataProvider.cs:74-80), unwraps
ICollection<T> / IReadOnlyCollection<T> to get the real target type
(NavigationMetadataProvider.cs:106-116), and then asks the infrastructure-side
IDataSourceService.HaveIncludeSupport(declaringType, targetType) whether the two entities actually
live in the same place (NavigationMetadataProvider.cs:96-99). If they do, the navigation goes in
SupportedIncludes; if not, into UnsupportedIncludes. Results are cached in a
ConcurrentDictionary keyed by (entity type, NavigationType) so the reflection runs once per shape,
and that cache is deliberately instance-level rather than static
(NavigationMetadataProvider.cs:22-28): classification depends on the host's data-source
configuration, so a process hosting several service configurations (integration tests, for example)
must not share classification results across hosts. The crucial architectural point is where the EF
knowledge lives: the Application layer classifies "what should be included" without referencing
Microsoft.EntityFrameworkCore at all, and the only component that knows the physical topology is
IDataSourceService at the Infrastructure
boundary ([Rubric §3, Clean Architecture], [Rubric §8, Data Architecture]).
Once the metadata exists, the
EntityQueryPipeline (Group 03) executes it
via a two-path strategy, and reading its real code
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:14) is the
clearest way to see how the metadata earns its keep. Both paths share a front half,
ApplyIncludesCriteriaAndFilters (EntityQueryPipeline.cs:116). Path 1 (server-side includes):
if there are SupportedIncludes, each becomes an EF Include call through the queryable executor
(EntityQueryPipeline.cs:134-135), and, importantly, that Include routes through the one
split-query heuristic, which switches to AsSplitQuery if any of them is a child collection
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/EFQueryableExecutor.cs:19-22,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/SpecificationEvaluator.cs:87-103).
That split-query switch is not cosmetic: paginating a single-query collection-Include makes EF apply
Skip/Take to the JOIN-expanded row set, which truncates child rows, and the comment above the
include loop records exactly that (EntityQueryPipeline.cs:129-133).
After includes, specification criteria and dynamic filters are applied before materialization so
the database does the filtering (EntityQueryPipeline.cs:137-144). Path 2 (manual navigation
loading): the moment UnsupportedIncludes.Count != 0 the pipeline cannot trust a JOIN
(EntityQueryPipeline.cs:55-56), so ExecuteWithManualNavigationAsync (EntityQueryPipeline.cs:154)
sorts server-side with a key tie-break for paginated reads (EntityQueryPipeline.cs:166-168),
applies paging or, for an unpaginated read, caps the result set at the MaxUnboundedResultLimit
ceiling of 1000 rows (EntityQueryPipeline.cs:25, defined as
MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:27;
EntityQueryPipeline.cs:172-182), materializes
that bounded page, and then invokes a navigation-populator delegate on it
(EntityQueryPipeline.cs:184-188) to fill in the cross-source relationships. The manual-load cost is
paid on one page of parents, not the whole table, and never as an N+1.
That delegate is the extension point to the second half of the chapter. Its signature,
Func<IReadOnlyCollection<TEntity>, NavigationMetadata, bool, bool, CancellationToken, Task>
(EntityQueryPipeline.cs:45), is exactly the shape of
INavigationPopulator<in TEntity>
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationPopulator.cs:9), the
per-entity port a module implements to load its own cross-source navigations
(INavigationPopulator.cs:20-25). The in variance makes it contravariant on the entity type; the
boolean pair mirrors the metadata provider's so a populator only loads what the caller asked for.
Entities with no cross-source navigations do not need a real implementation: the framework
supplies NullNavigationPopulator<TEntity>
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NullNavigationPopulator.cs:13), a
textbook Null Object whose PopulateAsync is a single Task.CompletedTask
(NullNavigationPopulator.cs:16-21), so the pipeline always has some populator to call and never
branches on null ([Rubric §2, Design Patterns]). AddApplication() registers it as the
open-generic default for every entity,
services.TryAdd(ServiceDescriptor.Scoped(typeof(INavigationPopulator<>), typeof(NullNavigationPopulator<>)))
(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:58), so a module registers a
closed INavigationPopulator<TEntity> only for an entity that actually has a cross-data-source
navigation, and the container prefers that closed registration over the default. The framework's own
push-notification entity registers no closed populator and relies on that open-generic default
(MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:45-46). The default
is not a silent hole: NullNavigationPopulator also implements
INavigationPopulatorCoverage
(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationPopulatorCoverage.cs:13)
with Handles returning false (NullNavigationPopulator.cs:24), and the
NavigationPopulatorStartupValidator
hosted service
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:36)
classifies every mapped entity's [Navigation] properties through the same NavigationMetadataProvider
and throws from StartAsync when an unsupported navigation is left on a populator that does not
handle it (NavigationPopulatorStartupValidator.cs:46-58). A cross-source navigation with no loader
therefore fails the host at start instead of reading back empty.
The actual batch loading is done by NavigationLoader
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationLoader.cs:39), a static helper
that exists to kill the N+1 problem. It exposes two methods: LoadFKPropertyAsync
(NavigationLoader.cs:77, a reference navigation: the parent holds an optional key of one related
entity, e.g. Product.Category) and LoadChildrenPropertyAsync (NavigationLoader.cs:137,
one-to-many, children hold the parent's FK, e.g. Order to OrderLines). The reference loader reads
the parent's key through a Func<TEntity, object?> (NavigationLoader.cs:79), so a nullable
value-type key and a nullable string key are both written p => p.CategoryId, and a non-null key of
the wrong type throws (NavigationLoader.cs:218-226). Both follow the same shape: collect the distinct
keys across all parents (NavigationLoader.cs:91-92, NavigationLoader.cs:152-155), short-circuit
when there are none by assigning every parent null or an empty list respectively
(NavigationLoader.cs:94-102, NavigationLoader.cs:157-165), then hand the keys to one shared private
LoadBoundedAsync (NavigationLoader.cs:187). That method builds a keys.Contains(child.Key)
predicate as an expression tree at runtime so it translates to one WHERE ... IN (...) statement
(NavigationLoader.cs:195-201) and runs it once through an
IReadRepository<TEntity, TIdentifierType>
as a BoundedChildLoad<TChildEntity, TChildIdentifierType>
specification (NavigationLoader.cs:203-205). BoundedChildLoad is a private nested
QuerySpecification (NavigationLoader.cs:232) that sets the criteria, orders by the child Id so
the ceiling is deterministic, and pages 0 to MaxChildRowsPerLoad + 1 (NavigationLoader.cs:236-241);
it never calls WithTracking, so the read stays untracked
(MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/QuerySpecification.cs:77). Every load is
bounded: MaxChildRowsPerLoad is ten children per parent at the pipeline's parent ceiling, 10,000
rows (NavigationLoader.cs:45), and the one extra row read lets an overflow be detected server-side
and thrown as an InvalidOperationException naming the relationship, never returned as a silently
truncated collection (NavigationLoader.cs:207-212). The loader then groups the results into a lookup
dictionary (NavigationLoader.cs:107-110, NavigationLoader.cs:171-174) and assigns each parent its
match or slice via a callback, O(1) per parent after one query for the whole batch
(NavigationLoader.cs:112-117, NavigationLoader.cs:176-179, [Rubric §12, Performance & Scalability]). A fields= projection is applied by the pipeline only after the populator ran, so
these loads always read whole child entities (NavigationLoader.cs:35-36). The compiled grouping
selectors are cached in a static ConcurrentDictionary (NavigationLoader.cs:51) keyed by source
type plus a parameter-name-independent member path (NavigationLoader.cs:250-282), so repeated calls
for the same selector skip Expression.Compile().
Writing a populator by hand for every entity would mean repeating the "is this navigation requested?
is it unsupported? which loader?" boilerplate per entity, which is what the declarative layer
removes. A navigation is described once as an
INavigationDescriptor<in TEntity>
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/INavigationDescriptor.cs:10), a
small strategy object carrying a PropertyName that must match the EF property name
(INavigationDescriptor.cs:13), a RequiresChildren flag (INavigationDescriptor.cs:19), and a
single LoadAsync(entities, IUnitOfWork, cancellationToken) method (INavigationDescriptor.cs:24-27).
There are two concrete descriptors, structurally twins:
ChildNavigationDescriptor<TEntity, TParentId, TChild, TChildId>
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/ChildNavigationDescriptor.cs:15)
for collections (RequiresChildren => true at ChildNavigationDescriptor.cs:25, delegating to
NavigationLoader.LoadChildrenPropertyAsync at ChildNavigationDescriptor.cs:37-47) and
FKNavigationDescriptor<TEntity, TChild, TChildId>
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/FKNavigationDescriptor.cs:16)
for references (RequiresChildren => false at FKNavigationDescriptor.cs:25, constrained only
where TChildId : notnull at FKNavigationDescriptor.cs:19 so the related key may be a value type or
a string, with a Func<TEntity, object?> ParentKeySelector that reads either kind of nullable key
at FKNavigationDescriptor.cs:33, delegating to NavigationLoader.LoadFKPropertyAsync at
FKNavigationDescriptor.cs:45-59). Each
descriptor's required init properties, the key selector, the child-FK expression (kept as an
Expression<Func<...>> precisely so NavigationLoader can turn it into the WHERE ... IN predicate),
and the assign callback mean an incomplete descriptor cannot even be constructed
(ChildNavigationDescriptor.cs:22-34, FKNavigationDescriptor.cs:22-42, [Rubric §1, SOLID],
[Rubric §15, Best Practices & Code Quality]). Both resolve their child repository from
IUnitOfWork at load time rather than injecting one
(ChildNavigationDescriptor.cs:45, FKNavigationDescriptor.cs:56).
The generic DeclarativeNavigationPopulator<TEntity>
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/DeclarativeNavigationPopulator.cs:22)
then drives a list of those descriptors: it takes an IUnitOfWork, an
IReadOnlyList<INavigationDescriptor<TEntity>> and an ILogger<DeclarativeNavigationPopulator<TEntity>>
as primary-constructor parameters (DeclarativeNavigationPopulator.cs:22-25) and implements both
INavigationPopulator<TEntity> and INavigationPopulatorCoverage (DeclarativeNavigationPopulator.cs:26).
Its PopulateAsync early-exits when there are no parents or no unsupported includes
(DeclarativeNavigationPopulator.cs:38-39), builds an ordinal HashSet<string> of the unsupported
property names (DeclarativeNavigationPopulator.cs:41-43), and for each descriptor loads it only when
the requested kind matches RequiresChildren and the property is actually in the unsupported set
(DeclarativeNavigationPopulator.cs:45-52). It then logs a warning for every unsupported navigation no
descriptor handles (DeclarativeNavigationPopulator.cs:54-57, a source-generated [LoggerMessage] at
DeclarativeNavigationPopulator.cs:76-79), the request-time backstop for a host whose start-up check
did not run. Its Handles answers the coverage question from the descriptor list: a descriptor covers a
navigation when the property names match ordinally and RequiresChildren agrees with the navigation
being a ChildCollection (DeclarativeNavigationPopulator.cs:66-74). Adding a new cross-source
navigation becomes "add one descriptor", not "write a new class" ([Rubric §15, Best Practices & Code Quality]). The class is declared public partial and left unsealed, so a module populator can
subclass it with its own descriptor list or a host can construct it directly.
End to end, the runtime flow for a list query is: a module query handler asks the
EntityQueryService<TEntity, TEntityDTO, TIdentifierType>
to run; the service calls NavigationMetadataProvider.BuildIncludes<TEntity> to get the
supported/unsupported split
(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:344); it hands that
split plus its module's injected INavigationPopulator<TEntity> (as the method-group delegate
NavigationPopulator.PopulateAsync) to EntityQueryPipeline.ExecuteAsync
(EntityQueryService.cs:406-411); the pipeline JOINs the supported navigations and, if any are
unsupported, materializes the page and calls the populator; the populator (almost always a
DeclarativeNavigationPopulator built from descriptors) iterates its descriptors and calls
NavigationLoader once per cross-source navigation. The same metadata also gates the service's keyed
by-id fast path: requested includes alone do not disqualify a keyed read, but a single unsupported
include does, because only the pipeline's populator can batch-load across physical sources
(EntityQueryService.cs:265-269). In the current ADC tree no module registers a populator of its own:
the Conference query services still take an INavigationPopulator<TEntity>, for example
INavigationPopulator<Session> in
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/SessionEntityQueryService.cs:20,
and each resolves to the open-generic NullNavigationPopulator default, because no ADC source file
references DeclarativeNavigationPopulator or a navigation descriptor. The declarative path is
exercised in Common's own tests, where a DeclarativeNavigationPopulator<PopulatorOrder> is
constructed directly to cover a cross-source navigation
(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Navigation/NavigationPopulatorStartupValidatorTests.cs:81).
Two architectural threads are worth holding onto as you read the per-type sections. First, this
subsystem is why the database-per-service split is feasible without rewriting query code
([Rubric §7, Microservices Readiness]): when a relationship's ends move to different sources, the EF
model's CrossDataSourceDegradeConvention
(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/CrossDataSourceDegradeConvention.cs:34)
drops the relationship and ignores the CLR navigation members, routing runtime navigation "through the
existing INavigationPopulator batch-loading machinery instead"
(CrossDataSourceDegradeConvention.cs:16-18), the metadata provider starts reporting that navigation
as unsupported, and the populator path picks it up automatically. The application code that issued the
query never changes, and when every entity resolves to the same physical source the convention is a
structural no-op (CrossDataSourceDegradeConvention.cs:26-30). Second, the design is a clean
illustration of keeping policy out of the domain: the what (a [Navigation] marker) lives in
Domain, the whether (supported versus unsupported) is computed in Application from an Infrastructure
capability check, and the how (batch SQL) is a static helper. Three responsibilities, three layers,
no EF leakage upward ([Rubric §3, Clean Architecture],
ADR-002). The trade-off ADR-002
itself names is honest: for a pure single-SQL-database host where Include always works, this is an
extra abstraction layer, but it costs nothing at runtime there, because the populator is only invoked
when the metadata actually reports an unsupported include, and otherwise the NullNavigationPopulator
no-ops.
NavigationAttribute
MMCA.Common.Domain ·
MMCA.Common.Domain.Attributes·MMCA.Common/Source/Core/MMCA.Common.Domain/Attributes/NavigationAttribute.cs:10· Level 0 · class (sealed attribute)
- What it is: marks a domain entity property as a navigation (a relationship to another entity), with a single flag distinguishing a collection from a single reference.
- Depends on:
System.Attribute(BCL) only. No first-party dependencies at all, which is the point. - Concept introduced, navigation metadata declared in the domain instead of read from EF.
[Rubric §2, Design Patterns](assesses whether patterns are idiomatic and solve a real problem) and[Rubric §3, Clean Architecture](assesses that dependencies point inward and the domain/application core stays framework-free). ADR-002 is the governing decision: the Application layer needs to know an entity's navigations (to build EFIncludepaths and field projections) without referencing Infrastructure or EF Core. Declaring navigations with a domain-level attribute letsNavigationMetadataProviderdiscover them by reflecting over the domain model, so the dependency arrow keeps pointing inward. The doc comment (MMCA.Common/Source/Core/MMCA.Common.Domain/Attributes/NavigationAttribute.cs:3-8) states exactly that: discovery is decoupled from EF Core's own metadata. - Walkthrough
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)](line 9).Inherited = falsemeans a derived entity must redeclare its own navigations rather than silently inheriting a base type's, so discovery is explicit rather than accidental.AllowMultiple = falsemeans one navigation classification per property.public bool IsCollection { get; init; }(line 16):truefor a one-to-many child collection,false(the default) for a many-to-one FK reference.init-only, so the classification is fixed at the attribute-application site.
- Why it's built this way: reading EF's own model metadata would force the Application layer to
reference
Microsoft.EntityFrameworkCore. A plain domain attribute costs one reflection pass (cached) and buys a framework-free core, which is the concrete §3 win behind ADR-002. The singleIsCollectionboolean is the same FK-versus-collection axis thatNavigationTypenames one level up. - Where it's used: applied on domain entity properties (for example
MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Domain/Speakers/Speaker.cs:77and:72tagSpeakerCategoryItemsandSpeakerQuestionAnswerswith[Navigation(IsCollection = true)], andMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Domain/Sponsors/Sponsor.cs:48tags theEventreference with a bare[Navigation]). Read byNavigationMetadataProvider(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:74) to build the metadata every other type in this chapter consumes.
NavigationType
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationMetadata.cs:6· Level 0 · enum
- What it is: a two-value enum classifying navigation properties.
ForeignKeyis a single-reference many-to-one (for exampleSponsor.Event);ChildCollectionis a one-to-many (for exampleSpeaker.SpeakerCategoryItems). - Depends on: BCL only. It shares the file
INavigationMetadata.cswithNavigationPropertyInfoandINavigationMetadata. - Concept:
[Rubric §8, Data Architecture](assesses a deliberate persistence and query strategy). The two kinds are loaded by two different mechanisms, so the classification has to survive from the domain attribute all the way to the loader: FK navigations resolve by matching a parent's nullable FK to a child key, child collections resolve by matching children's FK to the parent key. Those are the two methods onNavigationLoader, and the two descriptor classes at the end of this chapter. - Walkthrough:
ForeignKey(line 9),ChildCollection(line 12). No explicit ordinals are assigned, so the values are the implicit0and1and every branch in the codebase switches on the names, not the numbers. - Where it's used:
NavigationMetadataProviderderives it fromNavigationAttribute.IsCollection(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:78), stamps it onto eachNavigationPropertyInfoit builds (line 90), and uses it as half of the provider's cache key (line 28) so the FK and child-collection views of one entity are computed and memoized separately.
NavigationPropertyInfo
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationMetadata.cs:23· Level 1 · record class (sealed, positional)
- What it is: the metadata unit for a single navigation property: its CLR name, its kind, the entity type that declares it, and the entity type it targets.
- Depends on:
NavigationType(Level 0, same file, line 6) andSystem.Type(BCL). - Concept:
[Rubric §2, Design Patterns](ADR-002). The query pipeline decides per navigation whether EF canIncludeit (both ends in one data source) or whether a populator must batch-load it (the ends are split).NavigationPropertyInfocarries precisely the four facts that decision needs, andDeclaringEntityType/TargetEntityTypeare what get handed to the data-source capability check. - Walkthrough: four positional members (lines 23-28).
PropertyNameis the CLR property name on the declaring entity, and it is the join key against a descriptor'sPropertyNamelater on.Typeis theNavigationType.DeclaringEntityTypeandTargetEntityTypeareSystem.Type, and the target is unwrapped from collection generics: for a property typedIReadOnlyCollection<SpeakerCategoryItem>the target isSpeakerCategoryItem, not the collection (the unwrapping happens inNavigationMetadataProvider.UnwrapCollectionType,MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:106-116, which handlesICollection<T>andIReadOnlyCollection<T>). Being arecord classgives value equality for free, so two infos describing the same navigation compare equal. - Where it's used: constructed by
NavigationMetadataProvider(line 90) and accumulated into the two lists ofINavigationMetadata/NavigationMetadata.
INavigationMetadata
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationMetadata.cs:34· Level 2 · interface
- What it is: the read-only view that splits an entity's navigations into two buckets, those EF
Core can eager-load with
.Include()and those that require manual batch loading. - Depends on:
NavigationPropertyInfoand, transitively,NavigationType(same file, Levels 1 and 0). - Concept reinforced, the per-entity view of
ADR-002.
[Rubric §2, Design Patterns]and[Rubric §8, Data Architecture]: a navigation whose two ends live in different physical data sources cannot become a SQL JOIN, so it has to be a second query. This two-list split is that routing decision, computed once and then obeyed by the whole query path.[Rubric §7, Microservices Readiness]is equally in play: a navigation lands inUnsupportedIncludesexactly when database-per-service (ADR-006) has separated its ends, so this bucketing is what lets an extracted module keep its object graph hydrated without cross-database foreign keys. - Walkthrough: two members,
SupportedIncludes(line 37) andUnsupportedIncludes(line 40), bothIReadOnlyList<NavigationPropertyInfo>. The interface is purely a view; it declares no mutators at all, which is what forces population to go through the concrete builder below. - Where it's used: implemented by
NavigationMetadata. Consumers read the two lists rather than the interface itself in most call sites, because the query path passes the concrete builder type around (see the caveat on the next section).
NavigationMetadata
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/NavigationMetadata.cs:9· Level 3 · class (sealed)
- What it is: the concrete mutable builder behind
INavigationMetadata. It holds twoList<NavigationPropertyInfo>(supported and unsupported) and exposes them read-only while keeping every mutatorinternal. - Depends on:
INavigationMetadata(Level 2, the interface it implements) andNavigationPropertyInfo(Level 1). - Concept reinforced, builder with a read-only public face.
[Rubric §1, SOLID](the public surface is the minimum a caller needs) and[Rubric §8, Data Architecture]. The two backing lists are private and collection-initialized to[](lines 11-12); the twoIReadOnlyList<...>properties project them (lines 15, 18); the four add methods areinternal(lines 22, 26, 30, 34).internalvisibility is the enforcement mechanism: only code insideMMCA.Common.Applicationcan fill an instance, which in practice meansNavigationMetadataProviderand nothing else. Every module-authored populator receives a fully built instance and can only read it. - Walkthrough
_supportedIncludes/_unsupportedIncludes(lines 11-12): the two backing lists.SupportedIncludes(line 15) /UnsupportedIncludes(line 18): theIReadOnlyList<...>projections satisfying the interface.AddSupported(line 22) andAddUnsupported(line 26): single-item mutators, used byNavigationMetadataProvider.ClassifyNavigationProperty(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:96-99) right after the data-source capability check decides which bucket a navigation belongs in.AddSupportedRange(line 30) andAddUnsupportedRange(line 34): the bulk mutators used byBuildIncludes(same file, lines 38-39 and 45-46) to merge the cached per-kind metadata into the per-request instance.
- Why it's built this way: the classification is expensive (reflection over every public property
plus a data-source lookup) and stable per
(entity type, NavigationType), so the provider caches a builtNavigationMetadataper key and copies ranges out of it into a fresh instance per request. A mutable builder with an immutable public face is what makes sharing the cached instance safe. - Where it's used: built by
NavigationMetadataProvider, threaded through theEntityQueryPipeline, and passed by value into everyINavigationPopulator<in TEntity>'sPopulateAsync. - Caveats: the populator contract takes the concrete
NavigationMetadata, notINavigationMetadata(MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationPopulator.cs:22). The interface therefore documents the shape but is not the type most consumers actually program against.
BoundedChildLoad<TChildEntity, TChildIdentifierType>
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationLoader.cs:232· Level 4 · class (private, sealed, nested inNavigationLoader)
- What it is: the one query shape every
NavigationLoaderload runs: a specification carrying the batchIN (...)criteria, a deterministic order, and a row ceiling one pastNavigationLoader.MaxChildRowsPerLoad. - Depends on:
QuerySpecification<TEntity, TIdentifierType>(Level 3, the base whoseAddOrderByandApplyPagingit calls) andAuditableBaseEntity<TIdentifierType>(the constraint onTChildEntity, line 233). BCL:System.Linq.Expressions. - Concept: a bounded read expressed as a specification, the pattern taught in the
QuerySpecification<TEntity, TIdentifierType>section.[Rubric §12, Performance & Scalability]assesses whether reads have an upper bound; this type is where the navigation loader's bound is applied, server-side. - Walkthrough
- Constructor (lines 236-241): stores the caller's criteria (line 238), orders by the child key
with
AddOrderBy(child => child.Id)(line 239), and pages withApplyPaging(0, MaxChildRowsPerLoad + 1)(line 240), so at most 10,001 rows come back. Criteria(line 243): overridden as a get-only property set once in the constructor.- It never calls
WithTracking(), so the read stays untracked:AsTrackingdefaults tofalse(MMCA.Common/Source/Core/MMCA.Common.Domain/Specifications/QuerySpecification.cs:77, opted in only throughWithTracking()at line 132).
- Constructor (lines 236-241): stores the caller's criteria (line 238), orders by the child key
with
- Why it's built this way: the doc comment (lines 228-231) gives both reasons. Ordering by the
child key makes the ceiling deterministic (the same rows fall inside it on every run), and reading
one row past the ceiling lets
LoadBoundedAsyncdetect an overflow and throw (NavigationLoader.cs:207-212) without materializing everything that matched. - Where it's used: constructed only by
NavigationLoader.LoadBoundedAsync, which passes it toIReadRepository.ListAsync(NavigationLoader.cs:203-205). Beingprivate, it is invisible outsideNavigationLoader.
INavigationMetadataProvider
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/INavigationMetadataProvider.cs:9· Level 4 · interface
- What it is: the contract that inspects an entity type and classifies each of its navigation
properties as supported (loadable via EF Core
.Include()) or unsupported (needs manual loading), based on whether the two entities share a JOIN-capable data source. - Depends on:
NavigationMetadata(Level 3, the return type); no other first-party dependency in the interface. - Concept introduced, include-capability classification.
[Rubric §8, Data Architecture]assesses whether the persistence strategy adapts to the physical store; in a database-per-service (ADR-006) or polyglot (ADR-018) setup, two related entities may live in different stores, so an.Include()that generates a SQL JOIN cannot span them. This provider is where that "can EF JOIN these two?" decision is made, up front, before the query pipeline runs. - Walkthrough: one method,
NavigationMetadata BuildIncludes<TEntity>(bool includeFKs, bool includeChildren)(INavigationMetadataProvider.cs:19), building the classification for the requested navigation kinds (FK references and/or child collections) onTEntity. There is noCancellationTokenand noTask: the work is pure reflection plus a configuration lookup, so it is synchronous. - Where it's used: implemented by
NavigationMetadataProviderand registered as a singleton byAddApplication()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:49). Injected intoEntityQueryService<TEntity, TEntityDTO, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:37, null-guarded at line 48), which calls it three times, once per read shape: the by-id fast-path qualifierTryGetFastPathIncludes(line 265), which uses it to decide whether a keyed read can serve the requested includes; the list path inGetAllAsync(line 344); and the sharedBuildQueryAsync(line 788). ADC's per-entity query services (for exampleMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/SpeakerEntityQueryService.cs) pass it through to that base constructor.
INavigationPopulator<in TEntity>
MMCA.Common.Application ·
MMCA.Common.Application.Interfaces.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Navigation/INavigationPopulator.cs:9· Level 4 · interface
- What it is: the manual-loading port for navigations EF
Includecannot serve. An implementation receives a page of already-materialized entities and fills in their cross-source relationships. - Depends on:
NavigationMetadata(Level 3, a parameter on the single method). - Concept reinforced, the consumer side of
ADR-002.
[Rubric §2, Design Patterns](a Strategy resolved per entity type from DI) and[Rubric §7, Microservices Readiness](when a module is extracted and the related entity lives in another service's database, this is how the navigation still gets filled, with no cross-database FK). Thein TEntitycontravariance annotation means a populator written against a base entity type satisfies a request for a derived one. - Walkthrough: one method,
PopulateAsync(lines 20-25), takingIReadOnlyCollection<TEntity> entities, aNavigationMetadata, theincludeFKs/includeChildrenpair, and aCancellationToken. Two design choices are load bearing. First, the parameter is the whole page at once, which is what makes batch loading possible: one query per navigation for all parents, instead of one per parent. Second, the two booleans mirror the caller's original include request, so a populator loads only what was asked for rather than everything it knows how to load. - Why it's built this way: declaring the port in
Application(notInfrastructure) keeps the query pipeline that invokes it free of EF; implementations reach storage through the repository abstractions, viaNavigationLoader. See ADR-002. - Where it's used: injected into
EntityQueryService<TEntity, TEntityDTO, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:40, exposed as theNavigationPopulatorproperty at line 97 with a null guard). The service does not call it directly: it passes the method groupNavigationPopulator.PopulateAsyncinto the pipeline (lines 410 and 808), which declares the parameter as a plain delegate (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:45) and awaits it on the materialized page (line 199). A module registers a closedINavigationPopulator<TEntity>only for an entity with a cross-data-source navigation; every other entity resolves the open-generic default thatAddApplication()registers (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:52-58). ADC registers no closed populator, so its query services (for example theINavigationPopulator<Speaker>parameter atMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/SpeakerEntityQueryService.cs:20) receive that default.
NavigationMetadataProvider
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationMetadataProvider.cs:20· Level 5 · class (sealed)
- What it is: the concrete implementation of
INavigationMetadataProvider. It reflects over an entity's properties looking forNavigationAttribute, then asks the data-source service whether EF Core can.Include()each navigation or whether it needs manual loading, caching the answer per entity and navigation kind. - Depends on:
INavigationMetadataProvider(Level 4, the contract),IDataSourceService(theHaveIncludeSupportcheck),NavigationAttribute(the marker it reflects on),NavigationMetadata/NavigationPropertyInfo/NavigationType(the result types);System.ReflectionandSystem.Collections.Concurrent(BCL). - Concept introduced, reflection-driven, host-scoped include classification.
[Rubric §12, Performance & Scalability]assesses whether repeated expensive work is memoized; reflection over every entity's properties runs once per (entity type, navigation kind) and is cached. The cache is a deliberate instance field, notstatic: the doc comment (NavigationMetadataProvider.cs:22-27) explains that classification depends on the host's data-source configuration, so a process hosting multiple service configurations (integration tests) must not share classification results across hosts. That is[Rubric §14, Testability]paying for a small amount of per-host recomputation. - Walkthrough: constructed with an
IDataSourceService(line 20):private readonly ConcurrentDictionary<(Type EntityType, NavigationType NavType), NavigationMetadata> _cache(line 28), the per-instance memoization store.BuildIncludes<TEntity>(bool includeFKs, bool includeChildren)(lines 31-50) builds a freshNavigationMetadata, adding the FK-reference classifications whenincludeFKs(lines 35-40) and the child-collection ones whenincludeChildren(lines 42-47). The returned object is new per call even though the per-kind classifications are cached.GetNavigationProperties(lines 52-53), the cache lookup:_cache.GetOrAdd(...)computesBuildNavigationMetadataon a miss.BuildNavigationMetadata(lines 60-70) reflects over the entity's public instance properties (line 64) and classifies each.ClassifyNavigationProperty(lines 72-100) reads theNavigationAttributeand skips properties without one (lines 74-76), matches the attribute'sIsCollectionflag to the requestedNavigationType(lines 78-80), unwraps the collection element type (line 86), builds theNavigationPropertyInfo(line 90), then callsdataSourceService.HaveIncludeSupport(declaringEntityType.FullName, targetEntityType.FullName)(line 96; it compares full type names, notTypehandles) to sort the navigation into the supported or unsupported bucket (lines 97-99).UnwrapCollectionType(lines 106-116) pulls the element type out ofICollection<T>/IReadOnlyCollection<T>so the compatibility check sees the actual target entity.
- Why it's built this way: classifying by reflection keeps navigation configuration declarative (an
attribute on the property) rather than hand-registered, and caching per instance makes the
reflection cost a one-time hit while staying correct across differently configured hosts
(ADR-002 for the populator half
of this story; the class doc at lines 13-17 names
NavigationLoaderas what handles the unsupported bucket). - Where it's used: registered as the singleton
INavigationMetadataProviderbyAddApplication()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:49), so one cache lives per service provider. Through that interface it servesEntityQueryService<TEntity, TEntityDTO, TIdentifierType>(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:37), whoseBuildIncludesresult feedsEntityQueryPipelineand the by-id fast path decision (EntityQueryService.cs:265-266). The host-start checkNavigationPopulatorStartupValidatoralso constructs its own instance (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:71) so it classifies every mapped entity's navigations exactly as the query path does.
NullNavigationPopulator<TEntity>
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NullNavigationPopulator.cs:13· Level 5 · class (sealed, generic)
- What it is: the no-op
INavigationPopulator<in TEntity>, the framework's default populator for every entity, correct for any entity whose navigations are all EF-resolvable so nothing needs manual loading. - Depends on:
INavigationPopulator<in TEntity>(Level 4),INavigationPopulatorCoverage(Level 2, the coverage contract the host-start check reads),NavigationMetadata(Level 3) andNavigationPropertyInfo(Level 1), both in the signatures it satisfies. - Concept introduced, the Null Object pattern.
[Rubric §2, Design Patterns](assesses idiomatic pattern use). BecauseEntityQueryServicehard-requires a populator (it throwsArgumentNullExceptionwhen the constructor argument is null,MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:97), every entity must have one. A null-object implementation lets the pipeline keep one uniform call site with no null checks and no conditional branch: branchless polymorphism. - Walkthrough
PopulateAsync(lines 16-21): a single expression-bodied method whose entire body is=> Task.CompletedTask;. It accepts the full contract signature and ignores every argument.Handles(NavigationPropertyInfo navigation) => false(line 24): theINavigationPopulatorCoverageanswer, declaring that this populator loads no navigation at all.sealed, because there is nothing meaningful to extend.
- Why it's built this way: returning the already-completed
Task.CompletedTasksingleton (rather thanasyncwith no awaits) allocates nothing per call, so the no-op path costs essentially nothing on a hot query route ([Rubric §12, Performance & Scalability]). AnsweringfalsefromHandlesturns a silent gap into a startup failure: a cross-data-source navigation left on this default is reported by the host-start check instead of being returned empty. - Where it's used: registered once as the open-generic default by
AddApplication(),services.TryAdd(ServiceDescriptor.Scoped(typeof(INavigationPopulator<>), typeof(NullNavigationPopulator<>)))(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:58, with the rationale in the comment at lines 52-57). The container prefers any closedINavigationPopulator<TEntity>registration over it, so a module registers a populator only for an entity with a cross-source navigation. The notification composition relies on that default rather than a closed registration: the comment atMMCA.Common/Source/Core/MMCA.Common.Application/Notifications/DependencyInjection.cs:45-46states thatPushNotification's populator is the open-genericNullNavigationPopulator<>. Read byNavigationPopulatorStartupValidator, whoseIsHandledswitch (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:108-113) callsHandleson any populator that implements the coverage contract. - Caveats: because the default handles nothing, a host whose entity has an unsupported
navigation and no closed populator fails at start with an
InvalidOperationExceptionnaming each{Entity}.{Navigation} -> {Target}(NavigationPopulatorStartupValidator.cs:51-57). The check resolves no populator at all when nothing is unsupported, so a single-database host pays only one reflection pass.
INavigationDescriptor<in TEntity>
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/INavigationDescriptor.cs:10· Level 8 · interface
- What it is: the declaration of one navigation that needs manual loading: what it is called, which include flag turns it on, and how to load it for a batch of parents.
- Depends on:
IUnitOfWork(Level 7, passed intoLoadAsyncso the descriptor can resolve its own read repository rather than capturing one). - Concept introduced, the descriptor as a self-contained Strategy.
[Rubric §2, Design Patterns](Strategy: one descriptor per navigation, interchangeable behind the interface) and[Rubric §12, Performance](eachLoadAsyncis one batch query, not one per parent). Thein TEntitycontravariance mirrorsINavigationPopulator<in TEntity>'s. - Walkthrough
PropertyName(line 13): must match the EF/CLR property name, becauseDeclarativeNavigationPopulator<TEntity>matches it by string againstNavigationMetadata.UnsupportedIncludes.RequiresChildren(line 19):truemeans the caller'sincludeChildrengates this navigation,falsemeansincludeFKsdoes. One boolean instead of aNavigationTypevalue, because the populator only ever needs to pick between the two flags it was handed.LoadAsync(entities, unitOfWork, cancellationToken)(lines 24-27): batch-loads the navigation for all parents. TakingIUnitOfWorkas a parameter (rather than a constructor dependency) is what lets descriptors be plainnew-ed object literals in a populator's base-constructor argument list.
- Why it's built this way: declaring each cross-source navigation as a small descriptor lets one
generic populator serve every entity, and keeps the descriptor free of Infrastructure: it depends
only on
IUnitOfWork, an Application abstraction, and reaches storage throughNavigationLoaderand the read repository (ADR-002). - Where it's used: implemented by
ChildNavigationDescriptor<TEntity, TParentId, TChild, TChildId>andFKNavigationDescriptor<TEntity, TChild, TChildId>; consumed as anIReadOnlyList<INavigationDescriptor<TEntity>>byDeclarativeNavigationPopulator<TEntity>.
NavigationLoader
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationLoader.cs:39· Level 8 · class (static)
- What it is: the batch-loading engine. Two public static methods load a navigation for a whole
collection of parents with a single bounded
WHERE key IN (...)query each, and a cache keeps the compiled grouping delegates around. - Depends on:
AuditableBaseEntity<TIdentifierType>(Level 3, the constraint on the child type),IReadRepository<TEntity, TIdentifierType>(Level 5, the read port it queries through),QuerySpecification<TEntity, TIdentifierType>(Level 3, the base of its nestedBoundedChildLoad<TChildEntity, TChildIdentifierType>read) andEntityQueryPipeline(Level 7, whoseMaxUnboundedResultLimitsizes the row ceiling). BCL:System.Linq.ExpressionsandSystem.Collections.Concurrent. - Concept introduced, runtime expression-tree composition as N+1 prevention.
[Rubric §12, Performance & Scalability](assesses query efficiency, N+1 avoidance and bounded reads). Loading the category items for a page of 200 speakers one at a time is 200 round trips.NavigationLoaderinstead: (1) collects the distinct key values off the parent collection; (2) builds achild => keys.Contains(child.Key)expression tree by hand, so EF can translate it to a single SQLIN (...); (3) executes one bounded repository read; (4) groups the results into a dictionary keyed by that key and assigns each parent its match or its slice. The expression tree is built rather than written as a lambda because the key selector is supplied by the caller at runtime, so there is no compile-time lambda to write. The class remarks (lines 25-33) add the second rule: every load is bounded, and an overflow throws instead of returning a silently truncated collection. - Walkthrough
MaxChildRowsPerLoad(line 45):public const intset to10 * EntityQueryPipeline.MaxUnboundedResultLimit. The pipeline ceiling isKeysetPageRequest.MaxPageSize(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:25), which is 1,000 (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:27), so one load reads at most 10,000 child rows: ten per parent at the parent ceiling (doc comment, lines 41-44).CompiledExpressionCache(line 51): astatic readonly ConcurrentDictionary<string, Delegate>, process-wide, holding compiled selectors.LoadFKPropertyAsync(line 77) handles the reference direction (a parent holds an optional key of one related entity). It null-guardsparents,parentKeySelectorandassignAction(lines 87-89). The parent key selector is typedFunc<TEntity, object?>(line 79) so a nullable value-type key (int?) and a nullable reference key (string?) are both writtenp => p.CategoryId(doc comment, lines 62-67). Each parent's key is read once throughKeyOf(line 91) and the distinct present keys collected (line 92). If there are none it assignsnullto every parent and returns without querying (lines 94-102). Otherwise it runs oneLoadBoundedAsync(lines 104-105), groups by the compiled selector keeping the first match per key (g.First(), lines 107-110), and assigns each parent its match ornull, walking the keys it already read by index rather than re-running the selector (lines 112-117). The callback isAction<TEntity, TChildEntity?>(line 82), a single entity, and the constraint isTChildIdentifierType : notnull(line 85), sostringkeys work as well as value types.LoadChildrenPropertyAsync(line 137) handles the one-to-many direction (children hold the FK back to the parent). Same null guards (lines 148-150), then the distinct parent primary keys with no null filtering (lines 152-155), an empty-list early return when there are none (lines 157-165), oneLoadBoundedAsync(lines 167-168), grouping into lists (lines 171-174) and an assignment of each parent's list, or an empty one (lines 176-179). The constraint isTParentIdentifierType : notnull(line 144).LoadBoundedAsync(line 187), private and shared by both: builds theContainscall over the key list withExpression.Call(Expression.Constant(keys), List<TKey>.Contains, selector body)and wraps it in anExpression.Lambda<Func<TChildEntity, bool>>(lines 195-201), then reads throughchildRepository.ListAsync(new BoundedChildLoad<...>(criteria), ...)(lines 203-205). When more thanMaxChildRowsPerLoadrows come back it throwsInvalidOperationExceptionnaming the child type, the key's member path, the parent count and type, and the two remedies (fewer parents per page, or the children's own paged endpoint) (lines 207-212).KeyOf(line 218): a patternswitchover the selector's answer:nullis "no key", aTKeyis the key, and anything else throwsInvalidOperationExceptionnaming both types (lines 220-226).BoundedChildLoad<TChildEntity, TChildIdentifierType>(line 232): the nested specification each load runs, ordered by child key and paged to one row past the ceiling.GetOrCompileExpression(line 250) builds the cache key as"{TSource.FullName}:{memberPath}"(line 252) andGetOrAdds the compiled delegate.GetMemberPath(line 263) walks theMemberExpressionchain and joins the names with., so the key is independent of the lambda's parameter name:x => x.Category.Nameande => e.Category.Nameboth key on"Category.Name"(the doc comment at lines 258-262 says so). A non-member body falls back toexpression.ToString()(line 281). The overflow message reuses it (line 211).
- Why it's built this way: the predicate must stay an expression so EF translates it to
server-side SQL, while the grouping selector must be a compiled delegate because it runs in
memory over the materialized rows. Those are two different needs from the same
Expression<Func<TChild, TKey>>argument, which is why the type both composes it into the criteria and compiles it. Caching the compiled form means the compilation cost is paid once per distinct selector for the life of the process. The ceiling is enforced server-side with one extra row, so an overflow is detected without materializing the rest, and it throws rather than truncating so a caller never receives a partial collection that looks complete (remarks, lines 25-33). This is ADR-002's loading engine. - Where it's used: in
Source/, called through the two descriptor classes below (ChildNavigationDescriptoratMMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/ChildNavigationDescriptor.cs:41andFKNavigationDescriptoratMMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/FKNavigationDescriptor.cs:52), which is howDeclarativeNavigationPopulator<TEntity>reaches it. Exercised directly byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Navigation/NavigationLoaderTests.csandMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/DataSources/MultiSourceSqliteIntegrationTests.cs. - Caveats: the ceiling counts every row one load matches across the whole page of parents, so a
page whose children exceed 10,000 rows fails the request with
InvalidOperationExceptioninstead of returning data. Afields=projection does not shrink the read: the pipeline applies it in memory after the populator ran, so these loads always read whole child entities (remarks, lines 34-37). TheToString()fallback inGetMemberPathdoes include the parameter name, so two structurally identical non-member selectors written with different parameter names would occupy two cache entries. That is a duplicate entry, not a wrong result. The cache is unbounded, and its keys are derived from type names and member paths, both of which are finite per process.
The two concrete descriptors,
ChildNavigationDescriptorandFKNavigationDescriptor, are a structurally identical sibling pair: both are sealedINavigationDescriptor<in TEntity>data objects with fourrequired initmembers whoseLoadAsyncdelegates toNavigationLoader. TheChildNavigationDescriptorsection below teaches the shared shape in full;FKNavigationDescriptor(further down, after the populator that consumes them both) lists only what differs. They keep separate###headings so cross-links to each resolve.
ChildNavigationDescriptor<TEntity, TParentId, TChild, TChildId>
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/ChildNavigationDescriptor.cs:15· Level 9 · class (sealed)
- What it is: the one-to-many descriptor. It loads a child collection (for example
Speaker.SpeakerCategoryItems) by fetching every child whose FK matches one of the parents' primary keys. - Depends on:
INavigationDescriptor<in TEntity>(Level 8, the interface it implements),AuditableBaseEntity<TIdentifierType>(Level 3, the constraint onTChild),IUnitOfWork(Level 7, the source of the read repository), andNavigationLoader(Level 6). BCL:System.Linq.Expressions. - Concept introduced, configuration objects made total by
required.[Rubric §2, Design Patterns]and[Rubric §15, Best Practices & Code Quality](assesses whether the language's own guarantees are used instead of runtime checks). All four members arerequired init, so the compiler rejects a partially configured descriptor at the construction site; there is no validation code and no way to build an invalid one.[Rubric §4, DDD]also applies: the relationship is declared in the domain withNavigationAttributeand loaded in the Application layer here, with neither layer referencing EF. - Walkthrough
PropertyName(line 22):required, matched by string againstNavigationMetadata.UnsupportedIncludes.RequiresChildren => true(line 25): a hardcoded expression-bodied property, so this descriptor is always gated onincludeChildren.ParentKeySelector(line 28):Func<TEntity, TParentId>, a plain delegate because it runs in memory over already-materialized parents.ChildForeignKeySelector(line 31):Expression<Func<TChild, TParentId>>, an expression rather than a delegate becauseNavigationLoaderhas to translate it into the EFWherepredicate.AssignAction(line 34):Action<TEntity, List<TChild>>, the write-back callback that hands each parent its loaded children (the unit tests supply it as a constructor default atMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Navigation/ChildNavigationDescriptorTests.cs:30).LoadAsync(lines 37-47): a one-expression delegation toNavigationLoader.LoadChildrenPropertyAsync, resolving the child repository withunitOfWork.GetReadRepository<TChild, TChildId>()(line 45). Note the descriptor holds no repository of its own: it is a value that can be constructed in a field initializer and only touches storage when invoked.- Constraints (lines 17-19):
TParentId : notnull,TChild : AuditableBaseEntity<TChildId>,TChildId : notnull.
- Why it's built this way: ADR-002
requires cross-source includes to bypass EF
Includewithout the Application layer knowing about EF or the physical split. Making the descriptor a pure data object with a single delegating method is what lets a module declare its navigations as a collection literal in a constructor argument. - Where it's used: meant to be constructed inline in a per-entity populator's descriptor list. No
production module in ADC, Store or Helpdesk constructs one today; the only call site is the unit
test factory at
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Navigation/ChildNavigationDescriptorTests.cs:22-31. Consumed byDeclarativeNavigationPopulator<TEntity>.
DeclarativeNavigationPopulator<TEntity>
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/DeclarativeNavigationPopulator.cs:22· Level 9 · class (partial)
- What it is: the generic
INavigationPopulator<in TEntity>that drives a list ofINavigationDescriptor<in TEntity>. It decides when each descriptor runs; the descriptors know how. It also declares, from those same descriptors, which navigations it covers. - Depends on:
INavigationPopulator<in TEntity>(Level 4),INavigationPopulatorCoverage(Level 2),INavigationDescriptor<in TEntity>(Level 8),IUnitOfWork(Level 7),NavigationMetadata(Level 3) andNavigationPropertyInfo/NavigationType;Microsoft.Extensions.Loggingfor itsILogger<T>and source-generated log method. - Concept introduced, declaration over implementation.
[Rubric §2, Design Patterns](the descriptor list is a tiny declarative program that this class interprets by iteration) and[Rubric §15, Best Practices & Code Quality](adding a cross-source navigation means adding one object literal to a collection expression, not writing a class). The same list answers two questions: what to load at request time (PopulateAsync) and what is covered at host start (Handles), so the two cannot drift apart. The remarks (lines 12-17) state that contract. - Walkthrough
- Primary constructor (lines 22-26):
IUnitOfWork unitOfWork,IReadOnlyList<INavigationDescriptor<TEntity>> descriptorsandILogger<DeclarativeNavigationPopulator<TEntity>> logger, implementing bothINavigationPopulator<TEntity>andINavigationPopulatorCoverage(line 26). PopulateAsync(line 29) first throws on a nullnavigationMetadata(line 36). The guard at line 38 returns immediately whenentities.Count == 0ornavigationMetadata.UnsupportedIncludes.Count == 0: if every navigation is EF-resolvable, this populator does no work at all, even for an entity that declares descriptors.- Lines 41-43 build a
HashSet<string>of the unsupported include property names withStringComparer.Ordinal, making the per-descriptor membership test O(1) and case sensitive (ordinal, soPropertyNamemust match the CLR name exactly, whichnameof(...)guarantees at a well-formed call site). - Lines 45-52 iterate the descriptors in declaration order:
shouldLoad = descriptor.RequiresChildren ? includeChildren : includeFKs(line 47), and the descriptor'sLoadAsyncis awaited only whenshouldLoadand the descriptor'sPropertyNameis in the unsupported set (line 48). The two conditions are independent: the caller decides what it wants, the metadata decides what EF cannot do, and only the intersection is loaded..ConfigureAwait(false)on line 50 keeps the loop off the captured synchronization context. - Lines 54-57 then log a warning, through
LogUnhandledNavigation, for every unsupported navigation thatHandlesrejects, so a navigation no descriptor loads is named rather than silently returned empty. Handles(NavigationPropertyInfo navigation)(lines 66-74):truewhen some descriptor has the samePropertyName(ordinal) and the matching gate,RequiresChildrenequal tonavigation.Type == NavigationType.ChildCollection(line 70).LogUnhandledNavigation(lines 76-79): a[LoggerMessage]atLogLevel.Warning, which is why the class ispartial.
- Primary constructor (lines 22-26):
- Why it's built this way: the descriptors are awaited sequentially, one query per navigation
per page, which keeps a single
IUnitOfWork(and therefore a singleDbContext) safe to use, since EF Core forbids concurrent operations on one context. That is a correctness constraint, not an oversight: parallelizing here would require a repository per navigation.[Rubric §12, Performance & Scalability]still holds, because the cost is O(navigations) queries rather than O(parents). The warning path exists for a host whose hosted services did not run (the remarks at lines 14-16), where the start-up check never fired. - Where it's used: meant to be subclassed or constructed once per entity that has cross-source
navigations and registered as that entity's closed
INavigationPopulator<TEntity>, overriding the open-genericNullNavigationPopulator<TEntity>default.NavigationPopulatorStartupValidatorreads itsHandlesanswer at host start and names it in the failure message (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Navigation/NavigationPopulatorStartupValidator.cs:56). No production module in ADC, Store or Helpdesk currently registers one (their navigations are same-database, so the open-generic default covers them, as the comment atMMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Application/DependencyInjection.cs:24notes); the exercised call sites are the tests, for exampleMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Navigation/NavigationPopulatorStartupValidatorTests.cs:81. - Caveats: unlike the descriptors and
NullNavigationPopulator<TEntity>, this class is deliberately notsealed(line 22), because subclassing is an intended usage pattern. A subclass must now forward anILogger<DeclarativeNavigationPopulator<TEntity>>to the base constructor. An empty descriptor list is legal but yields a populator that handles nothing, so the host-start check treats it exactly like the null default.
FKNavigationDescriptor<TEntity, TChild, TChildId>
MMCA.Common.Application ·
MMCA.Common.Application.Services.Navigation·MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/FKNavigationDescriptor.cs:16· Level 9 · class (sealed)
- What it is: the many-to-one sibling of
ChildNavigationDescriptor. It loads a single reference (the class doc's example isProduct.Category, lines 8-11): the parent holds an optional key of one related entity, and each parent receives the related entity whose key matches, ornull. - Depends on: identical to its sibling:
INavigationDescriptor<in TEntity>,AuditableBaseEntity<TIdentifierType>,IUnitOfWork,NavigationLoader, andSystem.Linq.Expressions. - Concept: the same
required initdata-object Strategy taught in theChildNavigationDescriptorsection; only the differences are listed below. - Walkthrough, what differs
- Three type parameters instead of four (line 16): there is no
TParentId, because the join runs on the related entity's own key type, whichTChildIdalready names. - Constraint
TChildId : notnull(line 19), the same as the sibling's: the type-parameter doc (line 15) names a value type (int,Guid) or a reference type (string) as valid keys. ParentKeySelectorisFunc<TEntity, object?>(line 33): typedobjectso a nullable value-type key and a nullable reference key read the same way (p => p.CategoryId). A parent whose selector answersnullreceivesnull; a non-null value that is not aTChildIdthrows on load (doc comment, lines 27-32), inNavigationLoader'sKeyOf(MMCA.Common/Source/Core/MMCA.Common.Application/Services/Navigation/NavigationLoader.cs:224).ChildKeySelector(line 39),Expression<Func<TChild, TChildId>>, selects the key on the related entity that the parent's key matches, usually its primary key,c => c.Id(doc comment, lines 35-38). The sibling's equivalent member is namedChildForeignKeySelectorbecause there the selected column really is the foreign key.AssignActionisAction<TEntity, TChild?>(line 42): a single entity ornull, not a list.RequiresChildren => false(line 25), so this descriptor is gated onincludeFKs.LoadAsync(lines 45-59) null-guardsunitOfWork(line 50), then delegates toNavigationLoader.LoadFKPropertyAsync(line 52) instead of the children overload; theunitOfWork.GetReadRepository<TChild, TChildId>()resolution (line 56) is identical.PropertyName(line 22) is declared exactly as on the sibling.
- Three type parameters instead of four (line 16): there is no
- Where it's used: meant to be constructed inline in a per-entity populator's descriptor list for
a cross-source reference. No production module in ADC, Store or Helpdesk constructs one today;
the only call site is the unit test factory at
MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Navigation/FKNavigationDescriptorTests.cs:19-29, which wiresParentKeySelectortop => p.RelatedId(anint?, line 26 of that test) andChildKeySelectortoc => c.Id(line 27). Consumed byDeclarativeNavigationPopulator<TEntity>. - Caveats: because
ParentKeySelectorreturnsobject?, a selector of the wrong key type (for example along?against anintkey) compiles and fails only when the load runs, with anInvalidOperationExceptionnaming both types (NavigationLoader.cs:224). If more than one related row shares a key, the parent receives the first one (g.First(),NavigationLoader.cs:110), which is the lowestIdbecause each load is ordered by the child key (NavigationLoader.cs:239).
⬅ Notifications (Push + In-App Inbox + Email) • Index • API Hosting, Middleware, Idempotency & DTO/Contract Mapping ➡