Skip to content

Commit

Permalink
Scaffolding: Fix missing HasForeignKey when principal key is an alter…
Browse files Browse the repository at this point in the history
…nate key

Also adds coverage for more scenarios involving alternate principal keys

Fixes #29418
  • Loading branch information
bricelam committed Nov 3, 2022
1 parent 13965ec commit dd4a713
Show file tree
Hide file tree
Showing 3 changed files with 434 additions and 13 deletions.
23 changes: 12 additions & 11 deletions src/EFCore.Design/Extensions/ScaffoldingModelExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -287,16 +287,14 @@ public static bool IsHandledByDataAnnotations(this IIndex index, IAnnotationCode
this INavigation navigation,
IAnnotationCodeGenerator annotationCodeGenerator)
{
if (navigation.IsOnDependent
&& navigation.ForeignKey.PrincipalKey.IsPrimaryKey())
if (navigation.IsOnDependent)
{
yield return new AttributeCodeFragment(
typeof(ForeignKeyAttribute),
string.Join(", ", navigation.ForeignKey.Properties.Select(p => p.Name)));
}

if (navigation.ForeignKey.PrincipalKey.IsPrimaryKey()
&& navigation.Inverse != null)
if (navigation.Inverse != null)
{
yield return new AttributeCodeFragment(typeof(InversePropertyAttribute), navigation.Inverse.Name);
}
Expand All @@ -312,14 +310,11 @@ public static bool IsHandledByDataAnnotations(this IIndex index, IAnnotationCode
this ISkipNavigation skipNavigation,
IAnnotationCodeGenerator annotationCodeGenerator)
{
if (skipNavigation.ForeignKey!.PrincipalKey.IsPrimaryKey())
{
yield return new AttributeCodeFragment(
typeof(ForeignKeyAttribute),
string.Join(", ", skipNavigation.ForeignKey.Properties.Select(p => p.Name)));
yield return new AttributeCodeFragment(
typeof(ForeignKeyAttribute),
string.Join(", ", skipNavigation.ForeignKey.Properties.Select(p => p.Name)));

yield return new AttributeCodeFragment(typeof(InversePropertyAttribute), skipNavigation.Inverse.Name);
}
yield return new AttributeCodeFragment(typeof(InversePropertyAttribute), skipNavigation.Inverse.Name);
}

/// <summary>
Expand Down Expand Up @@ -720,6 +715,12 @@ valueGenerated switch
var hasForeignKey =
new FluentApiCodeFragment(nameof(ReferenceReferenceBuilder.HasForeignKey)) { IsHandledByDataAnnotations = true };

// HACK: Work around issue #29448
if (!foreignKey.PrincipalKey.IsPrimaryKey())
{
hasForeignKey.IsHandledByDataAnnotations = false;
}

if (foreignKey.IsUnique)
{
hasForeignKey.TypeArguments.Add(foreignKey.DeclaringEntityType.Name);
Expand Down
Loading

0 comments on commit dd4a713

Please sign in to comment.