From 970e8a4e8a3f78429ed813fa6f70136921b30a9d Mon Sep 17 00:00:00 2001 From: Andriy Svyryd Date: Wed, 17 Nov 2021 11:10:10 -0800 Subject: [PATCH] Update the foreign key builder after IsRequired() Fixes #26611 --- .../Metadata/Internal/InternalForeignKeyBuilder.cs | 14 +++++++++++++- .../ModelBuilding/ManyToOneTestBase.cs | 13 ++++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs b/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs index 901ad9085ed..b27dd1c66ec 100644 --- a/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs +++ b/src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs @@ -973,7 +973,19 @@ private static bool IsCompatible( Metadata.DeclaringEntityType.Model.ScopedModelDependencies?.Logger.AmbiguousEndRequiredWarning(Metadata); } - Metadata.SetIsRequired(required, configurationSource); + if (AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue26611", out var enabled) && enabled) + { + Metadata.SetIsRequired(required, configurationSource); + return this; + } + + IConventionForeignKey? foreignKey = Metadata; + var result = Metadata.DeclaringEntityType.Model.ConventionDispatcher.Track( + () => Metadata.SetIsRequired(required, configurationSource), ref foreignKey); + if (foreignKey != null) + { + return ((ForeignKey)foreignKey).Builder; + } return this; } diff --git a/test/EFCore.Tests/ModelBuilding/ManyToOneTestBase.cs b/test/EFCore.Tests/ModelBuilding/ManyToOneTestBase.cs index 2aff4f4504f..d9bbc51af58 100644 --- a/test/EFCore.Tests/ModelBuilding/ManyToOneTestBase.cs +++ b/test/EFCore.Tests/ModelBuilding/ManyToOneTestBase.cs @@ -1942,14 +1942,17 @@ public virtual void Creates_shadow_FK_property_with_non_shadow_PK() { b.HasMany() .WithOne(e => e.FirstNav) - .HasForeignKey("ShadowId"); + .HasForeignKey("ShadowId") + .IsRequired() + .HasAnnotation("Test", "foo"); }); - modelBuilder.FinalizeModel(); + var model = modelBuilder.FinalizeModel(); - Assert.Equal( - "ShadowId", - modelBuilder.Model.FindEntityType(typeof(Beta)).FindNavigation("FirstNav").ForeignKey.Properties.Single().Name); + var fk = model.FindEntityType(typeof(Beta)).FindNavigation("FirstNav").ForeignKey; + Assert.Equal("ShadowId", fk.Properties.Single().Name); + Assert.True(fk.IsRequired); + Assert.Equal("foo", fk["Test"]); } [ConditionalFact]