Skip to content

Commit 3859cd3

Browse files
committed
Usage of nameof in ForeignKeyAttribute/InversePropertyAttribute
1 parent c474d11 commit 3859cd3

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

src/EntityFrameworkCore.Scaffolding.Handlebars/HbsCSharpEntityTypeGenerator.cs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -401,9 +401,16 @@ private void GenerateForeignKeyAttribute(INavigation navigation)
401401
{
402402
var foreignKeyAttribute = new AttributeWriter(nameof(ForeignKeyAttribute));
403403

404-
foreignKeyAttribute.AddParameter(
405-
CSharpHelper.Literal(
406-
string.Join(",", navigation.ForeignKey.Properties.Select(p => p.Name))));
404+
if (navigation.ForeignKey.Properties.Count > 1)
405+
{
406+
foreignKeyAttribute.AddParameter(
407+
CSharpHelper.Literal(
408+
string.Join(",", navigation.ForeignKey.Properties.Select(p => p.Name))));
409+
}
410+
else
411+
{
412+
foreignKeyAttribute.AddParameter($"nameof({navigation.ForeignKey.Properties.First().Name})");
413+
}
407414

408415
NavPropertyAnnotations.Add(new Dictionary<string, object>
409416
{
@@ -423,7 +430,11 @@ private void GenerateInversePropertyAttribute(INavigation navigation)
423430
{
424431
var inversePropertyAttribute = new AttributeWriter(nameof(InversePropertyAttribute));
425432

426-
inversePropertyAttribute.AddParameter(CSharpHelper.Literal(inverseNavigation.Name));
433+
inversePropertyAttribute.AddParameter(
434+
!navigation.DeclaringEntityType.GetPropertiesAndNavigations().Any(
435+
m => m.Name == inverseNavigation.DeclaringEntityType.Name)
436+
? $"nameof({inverseNavigation.DeclaringEntityType.Name}.{inverseNavigation.Name})"
437+
: CSharpHelper.Literal(inverseNavigation.Name));
427438

428439
NavPropertyAnnotations.Add(new Dictionary<string, object>
429440
{

test/Scaffolding.Handlebars.Tests/ExpectedEntities.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ public partial class Product
9696
public byte[] RowVersion { get; set; }
9797
public int? CategoryId { get; set; }
9898
99-
[ForeignKey(""CategoryId"")]
99+
[ForeignKey(nameof(CategoryId))]
100100
[InverseProperty(""Product"")]
101101
public virtual Category Category { get; set; }
102102
}

0 commit comments

Comments
 (0)