Skip to content

Commit

Permalink
Update the foreign key builder after IsRequired()
Browse files Browse the repository at this point in the history
Fixes #26611
  • Loading branch information
AndriySvyryd committed Nov 17, 2021
1 parent 6fc3e17 commit f5d7895
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
8 changes: 7 additions & 1 deletion src/EFCore/Metadata/Internal/InternalForeignKeyBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -973,7 +973,13 @@ private static bool IsCompatible(
Metadata.DeclaringEntityType.Model.ScopedModelDependencies?.Logger.AmbiguousEndRequiredWarning(Metadata);
}

Metadata.SetIsRequired(required, configurationSource);
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;
}
Expand Down
13 changes: 8 additions & 5 deletions test/EFCore.Tests/ModelBuilding/ManyToOneTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1942,14 +1942,17 @@ public virtual void Creates_shadow_FK_property_with_non_shadow_PK()
{
b.HasMany<Beta>()
.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]
Expand Down

0 comments on commit f5d7895

Please sign in to comment.