From 32ca7e7aa318a7bff31a9b2460e248574f2a22c4 Mon Sep 17 00:00:00 2001 From: Andriy Svyryd Date: Tue, 9 Nov 2021 13:10:30 -0800 Subject: [PATCH] Avoid NRE in ForeignKeyAttributeConvention Fixes #26436 --- .../ForeignKeyAttributeConvention.cs | 2 +- .../DataAnnotationTestBase.cs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs b/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs index 6694cc571e6..fe14c220124 100644 --- a/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs +++ b/src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs @@ -345,7 +345,7 @@ var fkPropertiesOnDependentToPrincipal } } - return newRelationshipBuilder.HasForeignKey(fkPropertiesToSet, fromDataAnnotation: true); + return newRelationshipBuilder?.HasForeignKey(fkPropertiesToSet, fromDataAnnotation: true); } private static IConventionForeignKeyBuilder? SplitNavigationsToSeparateRelationships( diff --git a/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs b/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs index c7ebab2e2e6..4bb01051d1f 100644 --- a/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs +++ b/test/EFCore.Specification.Tests/DataAnnotationTestBase.cs @@ -1105,6 +1105,25 @@ protected class Profile4 public virtual Login4 User { get; set; } } + [ConditionalFact] + public virtual void Required_and_ForeignKey_to_ForeignKey_can_be_overridden() + { + var modelBuilder = CreateModelBuilder(); + + modelBuilder.Entity() + .HasOne(p => p.Profile) + .WithOne(p => p.User) + .HasForeignKey("ProfileId"); + + var model = Validate(modelBuilder); + + var loginFk = GetProperty(model, "ProfileId").GetContainingForeignKeys().Single(); + Assert.True(loginFk.IsRequired); // This will be False after #15898 is fixed + Assert.True(loginFk.IsRequiredDependent); + + Assert.False(GetProperty(model, nameof(Profile3.Profile3Id)).IsForeignKey()); + } + [ConditionalFact] public virtual void ForeignKey_to_nothing() {