Skip to content

Commit

Permalink
Avoid NRE in ForeignKeyAttributeConvention
Browse files Browse the repository at this point in the history
Fixes #26436
  • Loading branch information
AndriySvyryd authored Nov 9, 2021
1 parent 62dc53f commit 32ca7e7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ var fkPropertiesOnDependentToPrincipal
}
}

return newRelationshipBuilder.HasForeignKey(fkPropertiesToSet, fromDataAnnotation: true);
return newRelationshipBuilder?.HasForeignKey(fkPropertiesToSet, fromDataAnnotation: true);
}

private static IConventionForeignKeyBuilder? SplitNavigationsToSeparateRelationships(
Expand Down
19 changes: 19 additions & 0 deletions test/EFCore.Specification.Tests/DataAnnotationTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Login3>()
.HasOne(p => p.Profile)
.WithOne(p => p.User)
.HasForeignKey<Login3>("ProfileId");

var model = Validate(modelBuilder);

var loginFk = GetProperty<Login3>(model, "ProfileId").GetContainingForeignKeys().Single();
Assert.True(loginFk.IsRequired); // This will be False after #15898 is fixed
Assert.True(loginFk.IsRequiredDependent);

Assert.False(GetProperty<Profile3>(model, nameof(Profile3.Profile3Id)).IsForeignKey());
}

[ConditionalFact]
public virtual void ForeignKey_to_nothing()
{
Expand Down

0 comments on commit 32ca7e7

Please sign in to comment.