Repository navigation
Support "unconstrained" foreign key relationships - #38361
Conversation
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds support for “unconstrained” foreign keys (IsConstrained) across EF Core metadata, conventions, runtime model, query translation, migrations/snapshots, and provider defaults (Cosmos), with corresponding regression tests.
Changes:
- Introduces
IReadOnlyForeignKey.IsConstrained(plus configuration plumbing) and propagates it through runtime model creation/scaffolding. - Updates query translation to treat required-but-unconstrained relationships as optional (
IsEffectivelyRequired()), affecting join type/pruning. - Adds tests for metadata/configuration source behavior, runtime model preservation, migrations operations, query SQL, fixup semantics, and Cosmos defaults.
Reviewed changes
Copilot reviewed 43 out of 43 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| test/EFCore.Tests/Metadata/RuntimeModelTest.cs | New test ensuring IsConstrained persists into the runtime model. |
| test/EFCore.Tests/Metadata/Internal/InternalForeignKeyBuilderTest.cs | Tests for inversion and configuration-source precedence of IsConstrained. |
| test/EFCore.Tests/Metadata/Internal/ForeignKeyTest.cs | Tests default/set/reset + fluent API metadata wiring for IsConstrained. |
| test/EFCore.Sqlite.FunctionalTests/Query/AdHocMiscellaneousQuerySqliteTest.cs | Functional SQL assertions for join shape/pruning and save behavior for unconstrained FKs. |
| test/EFCore.Specification.Tests/TestUtilities/ModelAsserter.cs | Includes IsConstrained in model comparisons and copy logic. |
| test/EFCore.Relational.Tests/Migrations/Internal/MigrationsModelDifferTest.cs | Ensures unconstrained FKs don’t generate FK ops; changing to unconstrained drops constraint. |
| test/EFCore.InMemory.FunctionalTests/UnconstrainedForeignKeyFixupTest.cs | Fixup/change-tracking behavior tests for unconstrained relationships. |
| test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs | Snapshot roundtrip test for .IsConstrained(false). |
| test/EFCore.Cosmos.Tests/Metadata/Conventions/CosmosForeignKeyConventionTest.cs | Validates Cosmos defaults: non-owned unconstrained; owned remains constrained. |
| test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/No_NativeAOT/PrincipalBasePrincipalDerivedDependentBasebyteEntityType.cs | Baseline update emitting constrained: false in runtime model scaffolding. |
| test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/No_NativeAOT/DependentBaseEntityType.cs | Baseline update emitting constrained: false in runtime model scaffolding. |
| test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/ComplexTypes/PrincipalBaseEntityType.cs | Baseline update emitting constrained: false in runtime model scaffolding. |
| test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/BigModel/PrincipalBasePrincipalDerivedDependentBasebyteEntityType.cs | Baseline update emitting constrained: false in runtime model scaffolding. |
| test/EFCore.Cosmos.FunctionalTests/Scaffolding/Baselines/BigModel/DependentBaseEntityType.cs | Baseline update emitting constrained: false in runtime model scaffolding. |
| src/EFCore/Query/Internal/NavigationExpandingExpressionVisitor.ExpressionVisitors.cs | Switches join decisions from IsRequired to IsEffectivelyRequired(). |
| src/EFCore/Metadata/RuntimeForeignKey.cs | Stores and exposes IsConstrained in runtime FK metadata. |
| src/EFCore/Metadata/RuntimeEntityType.cs | Adds constrained parameter when constructing runtime foreign keys. |
| src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs | Adds builder APIs, configuration checks, and carries IsConstrained across FK rebuilds. |
| src/EFCore/Metadata/Internal/ForeignKey.cs | Adds IsConstrained state + config source + convention dispatch hook. |
| src/EFCore/Metadata/IReadOnlyForeignKey.cs | Adds IsConstrained and IsEffectivelyRequired() API and docs. |
| src/EFCore/Metadata/IMutableForeignKey.cs | Adds mutable IsConstrained API. |
| src/EFCore/Metadata/IConventionForeignKey.cs | Adds convention-setter + config-source access for IsConstrained. |
| src/EFCore/Metadata/Conventions/RuntimeModelConvention.cs | Propagates IsConstrained into runtime model foreign keys. |
| src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.cs | Adds dispatcher hook for constrainedness changes. |
| src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ImmediateConventionScope.cs | Executes constrainedness-changed conventions immediately. |
| src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.DelayedConventionScope.cs | Queues constrainedness-changed convention node for delayed execution. |
| src/EFCore/Metadata/Conventions/Internal/ConventionDispatcher.ConventionScope.cs | Adds abstract constrainedness-changed dispatch method. |
| src/EFCore/Metadata/Conventions/IForeignKeyConstrainednessChangedConvention.cs | New convention interface for constrainedness changes. |
| src/EFCore/Metadata/Conventions/ConventionSet.cs | Adds a convention list for FK constrainedness changes and wires add/replace/remove. |
| src/EFCore/Metadata/Builders/ReferenceReferenceBuilder`.cs | Adds fluent .IsConstrained() for generic 1:1 builder. |
| src/EFCore/Metadata/Builders/ReferenceReferenceBuilder.cs | Adds fluent .IsConstrained() for non-generic 1:1 builder. |
| src/EFCore/Metadata/Builders/ReferenceCollectionBuilder`.cs | Adds fluent .IsConstrained() for generic 1:* builder. |
| src/EFCore/Metadata/Builders/ReferenceCollectionBuilder.cs | Adds fluent .IsConstrained() for non-generic 1:* builder. |
| src/EFCore/Metadata/Builders/IConventionForeignKeyBuilder.cs | Adds convention builder methods for constrainedness set/check. |
| src/EFCore/EFCore.baseline.json | Updates public API baseline for new members. |
| src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs | Ensures “required FK” optimizations only for constrained relationships. |
| src/EFCore.Relational/Metadata/Internal/RelationalModel.cs | Avoids generating relational FK constraints when IsConstrained is false. |
| src/EFCore.Relational/Metadata/Conventions/SharedTableConvention.cs | Skips constraint-name slot allocation for unconstrained FKs. |
| src/EFCore.Design/Scaffolding/Internal/CSharpRuntimeModelCodeGenerator.cs | Emits constrained: false only when needed in runtime model codegen. |
| src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs | Emits .IsConstrained(false) in snapshot output when needed. |
| src/EFCore.Cosmos/Metadata/Conventions/Internal/CosmosConventionSetBuilder.cs | Registers Cosmos convention to default non-owned FKs to unconstrained. |
| src/EFCore.Cosmos/Metadata/Conventions/CosmosUnconstrainedForeignKeyConvention.cs | New Cosmos convention that sets non-ownership FKs to unconstrained. |
| src/EFCore.Cosmos/EFCore.Cosmos.baseline.json | Updates Cosmos public API baseline for new convention type. |
Comments suppressed due to low confidence (5)
test/EFCore.Sqlite.FunctionalTests/Query/AdHocMiscellaneousQuerySqliteTest.cs:1
- If nullable reference types are enabled (as they commonly are in EFCore test projects),
Principalwill trigger CS8618 (non-nullable property not initialized). To keep builds clean (and avoid warnings-as-errors), initialize with= null!;or make the navigation nullable (Principal13146?).
test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs:1 - This non-nullable navigation lacks an initializer and may produce CS8618 under nullable reference types. Consider
= null!;(common pattern in EFCore tests) or make it nullable.
test/EFCore.InMemory.FunctionalTests/UnconstrainedForeignKeyFixupTest.cs:1 - Both
Principalnavigations are non-nullable without initializers, which can cause CS8618 in projects with nullable enabled. Use= null!;or make them nullable (and adjust tests accordingly).
test/EFCore.InMemory.FunctionalTests/UnconstrainedForeignKeyFixupTest.cs:1 - Both
Principalnavigations are non-nullable without initializers, which can cause CS8618 in projects with nullable enabled. Use= null!;or make them nullable (and adjust tests accordingly).
test/EFCore.Cosmos.Tests/Metadata/Conventions/CosmosForeignKeyConventionTest.cs:1 - The non-nullable
Ownednavigation has no initializer and may trigger CS8618 when nullable reference types are enabled. Consider initializing with= null!;or make it nullable.
AndriySvyryd
left a comment
There was a problem hiding this comment.
Some minor comments below, but overall, a pretty good PR for a first-time community contributor 😆.
|
@ajcvickers CosmosModelBuilderGenericTest+CosmosGenericNonRelationship.Foreign_key_can_be_configured_as_unconstrained is failing |
Adds a provider-agnostic `IsConstrained` flag to foreign keys (default `true`), orthogonal to `IsRequired`. An unconstrained relationship exists in the model but is not backed by a guarantee that a set foreign key value references an existing principal. It is therefore always optional in queries even when the foreign key properties are non-nullable, and no database foreign key constraint is created. This is the natural shape for document databases (e.g. Azure Cosmos DB) and is now also available as an opt-in for relational providers. Public API: - `.IsConstrained(bool)` on `ReferenceCollectionBuilder`/`ReferenceReferenceBuilder` (and their generic variants). - `IsConstrained` on `IReadOnlyForeignKey`/`IMutableForeignKey`/`IConventionForeignKey`, with the usual convention plumbing, plus a new `IReadOnlyForeignKey.IsEffectivelyRequired()` helper (`IsRequired && IsConstrained`) that the query pipeline consults for join-shape decisions. Behavior when `IsConstrained` is `false`: - Query: the dependent-to-principal navigation is expanded with a LEFT JOIN, and a join is never elided on the assumption that the principal exists. `IsRequired` continues to govern column/property nullability. - Relational: no foreign key constraint is created in the relational model, so migrations emit no `AddForeignKey` (and flipping an existing relationship to unconstrained yields a `DropForeignKey`). The supporting index is unaffected, and the constraint name is not reserved when uniquifying names on a shared table. - Change tracking is unchanged: a required relationship still performs fixup, cascade delete, and conceptual-null handling exactly as a constrained one does. The only difference is that a set foreign key value is no longer assumed to match a tracked or stored principal. - Owned/embedded relationships remain constrained, since the principal is guaranteed to exist when the dependent is embedded in it. Azure Cosmos DB: all non-owned foreign keys now default to unconstrained, because Cosmos does not enforce foreign key constraints between documents. The flag round-trips through both the compiled model and the migrations snapshot. Breaking change (Cosmos): non-owned references are now treated as optional/unconstrained — queries over them emit optional joins and no longer assume the principal exists. To retain the previous behavior for a specific relationship, configure it with `.IsConstrained(true)`. Fixes dotnet#13146
- GetConstraintName now returns null for unconstrained foreign keys (AndriySvyryd), so PopulateForeignKeyConstraints and SharedTableConvention skip them via the existing null checks. Reverted the two scattered `!IsConstrained` guards. - Moved the runtime-model preservation test out of the standalone RuntimeModelTest into ModelBuilderTest.NonRelationshipTestBase (AndriySvyryd), adding IsConstrained to the TestReferenceCollectionBuilder test abstraction (generic + non-generic) to mirror IsRequired. - Fixed the "change change tracking" duplicated word in the IsConstrained doc. - Reworded the four builder IsConstrained docs so "optional" is scoped to query (the principal is not assumed to exist) rather than implying model requiredness, with a cross-reference to IReadOnlyForeignKey.IsConstrained.
…test The shared test reused the Order entity, whose Products navigation targets the [NotMapped] Product type. On relational/InMemory that navigation is ignored automatically, but Cosmos's CosmosRelationshipDiscoveryConvention treats navigations as owned by default, so a root Order left Order.Products unmapped and model validation failed. Ignore<Product>() in the test (matching the established pattern across the model-building tests). Harmless on relational; fixes Cosmos.
963fb5e to
a46e556
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 46 out of 46 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (5)
test/EFCore.Sqlite.FunctionalTests/Query/AdHocMiscellaneousQuerySqliteTest.cs:1
Dependent13146.Principalis non-nullable but not initialized, which will produce CS8618 under nullable reference types (and may fail the build if warnings are treated as errors). Also, for an unconstrained relationship the principal isn’t guaranteed to exist at runtime, so consider making this navigation nullable (Principal13146?) and/or initializing with a null-forgiving assignment (= null!;) to match the model semantics and suppress the warning.
test/EFCore.InMemory.FunctionalTests/UnconstrainedForeignKeyFixupTest.cs:1- These navigations are non-nullable but not initialized, so they will trigger CS8618 under nullable reference types (and may fail the build if warnings are treated as errors). Initialize them (e.g.,
= null!;) and/or make them nullable where appropriate (notably for unconstrained relationships where the principal may legitimately be absent).
test/EFCore.InMemory.FunctionalTests/UnconstrainedForeignKeyFixupTest.cs:1 - These navigations are non-nullable but not initialized, so they will trigger CS8618 under nullable reference types (and may fail the build if warnings are treated as errors). Initialize them (e.g.,
= null!;) and/or make them nullable where appropriate (notably for unconstrained relationships where the principal may legitimately be absent).
test/EFCore.Design.Tests/Migrations/Design/CSharpMigrationsGeneratorTest.ModelSnapshot.cs:1 UnconstrainedFkDependent.Principalis non-nullable but not initialized, which will produce CS8618 under nullable reference types. Since this test models an unconstrained FK (principal not guaranteed), consider making the navigation nullable and/or initializing with= null!;to avoid warnings and better reflect runtime behavior.
test/EFCore.Cosmos.Tests/Metadata/Conventions/CosmosForeignKeyConventionTest.cs:1Owner.Ownedis non-nullable but not initialized, which will produce CS8618 under nullable reference types (and may fail the build if warnings are treated as errors). Initialize the property (e.g.,= null!;) or make it nullable if the test doesn’t require non-nullability.
API review baseline changes for
|
|
Thank you so much @AndriySvyryd ! |
You should thank @ajcvickers (or Claude 😆) |
What is the best way to eliminate the index too? Some pointers for custom code would be appreciated, i.e. add an attribute and use similar code from #13146 (comment) to locate and remove the index? I'm using TPH inheritance as described in #13146 (comment) and either need the index on all fields (EntityId, EntityType, UserId) or for the index on only EntityId to be removed. Any suggestions would be welcome - right now I manually alter the migration script. |
Adds a provider-agnostic
IsConstrainedflag to foreign keys (defaulttrue), orthogonal toIsRequired. An unconstrained relationship exists in the model but is not backed by a guarantee that a set foreign key value references an existing principal. It is therefore always optional in queries even when the foreign key properties are non-nullable, and no database foreign key constraint is created.This is the natural shape for document databases (e.g. Azure Cosmos DB) and is now also available as an opt-in for relational providers.
Public API:
.IsConstrained(bool)onReferenceCollectionBuilder/ReferenceReferenceBuilder(and their generic variants).IsConstrainedonIReadOnlyForeignKey/IMutableForeignKey/IConventionForeignKey, with the usual convention plumbing, plus a newIReadOnlyForeignKey.IsEffectivelyRequired()helper (IsRequired && IsConstrained) that the query pipeline consults for join-shape decisions.Behavior when
IsConstrainedisfalse:IsRequiredcontinues to govern column/property nullability.AddForeignKey(and flipping an existing relationship to unconstrained yields aDropForeignKey). The supporting index is unaffected, and the constraint name is not reserved when uniquifying names on a shared table.Azure Cosmos DB: all non-owned foreign keys now default to unconstrained, because Cosmos does not enforce foreign key constraints between documents.
The flag round-trips through both the compiled model and the migrations snapshot.
Breaking change (Cosmos): non-owned references are now treated as optional/unconstrained — queries over them emit optional joins and no longer assume the principal exists. To retain the previous behavior for a specific relationship, configure it with
.IsConstrained(true).Fixes #13146