From 7ce664af397cf03460f0f2b43b17fe277af59492 Mon Sep 17 00:00:00 2001 From: David Boone Date: Thu, 23 May 2024 13:59:19 -0700 Subject: [PATCH] If relationship PrimaryProperties aren't primary key, generate HasPrincipalKey on relationshipo --- .../Templates/MappingClassTemplate.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/EntityFrameworkCore.Generator.Core/Templates/MappingClassTemplate.cs b/src/EntityFrameworkCore.Generator.Core/Templates/MappingClassTemplate.cs index 2ae568fe..1acce33e 100644 --- a/src/EntityFrameworkCore.Generator.Core/Templates/MappingClassTemplate.cs +++ b/src/EntityFrameworkCore.Generator.Core/Templates/MappingClassTemplate.cs @@ -224,6 +224,30 @@ private void GenerateRelationshipMapping(Relationship relationship) } CodeBuilder.Append(")"); + var primaryKeys = relationship.PrimaryProperties; + var nonPrimaryPrincipalKey = !primaryKeys + .Select(pp => relationship.PrimaryEntity.Properties.ByProperty(pp.PropertyName)) + .All(p => p.IsPrimaryKey ?? true); + + if (nonPrimaryPrincipalKey) + { + CodeBuilder.AppendLine(); + + CodeBuilder.Append(".HasPrincipalKey(t => "); + if (primaryKeys.Count > 1) + { + CodeBuilder.Append("new { "); + CodeBuilder.Append(string.Join(", ", primaryKeys.Select(pp => $"t.{pp.PropertyName.ToSafeName()}"))); + CodeBuilder.Append(" }"); + } + else + { + var propertyName = primaryKeys.First().PropertyName.ToSafeName(); + CodeBuilder.Append($"t.{propertyName}"); + } + CodeBuilder.Append(")"); + } + if (!string.IsNullOrEmpty(relationship.RelationshipName)) { CodeBuilder.AppendLine();