Skip to content

Commit e77c93c

Browse files
committed
If relationship PrimaryProperties aren't primary key, generate HasPrincipalKey on relationshipo
1 parent ab7c0a8 commit e77c93c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/EntityFrameworkCore.Generator.Core/Templates/MappingClassTemplate.cs

+24
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,30 @@ private void GenerateRelationshipMapping(Relationship relationship)
224224
}
225225
CodeBuilder.Append(")");
226226

227+
var primaryKeys = relationship.PrimaryProperties;
228+
var nonPrimaryPrincipalKey = !primaryKeys
229+
.Select(pp => relationship.PrimaryEntity.Properties.ByProperty(pp.PropertyName))
230+
.All(p => p.IsPrimaryKey ?? true);
231+
232+
if (nonPrimaryPrincipalKey)
233+
{
234+
CodeBuilder.AppendLine();
235+
236+
CodeBuilder.Append(".HasPrincipalKey(t => ");
237+
if (primaryKeys.Count > 1)
238+
{
239+
CodeBuilder.Append("new { ");
240+
CodeBuilder.Append(string.Join(", ", primaryKeys.Select(pp => $"t.{pp.PropertyName.ToSafeName()}")));
241+
CodeBuilder.Append(" }");
242+
}
243+
else
244+
{
245+
var propertyName = primaryKeys.First().PropertyName.ToSafeName();
246+
CodeBuilder.Append($"t.{propertyName}");
247+
}
248+
CodeBuilder.Append(")");
249+
}
250+
227251
if (!string.IsNullOrEmpty(relationship.RelationshipName))
228252
{
229253
CodeBuilder.AppendLine();

0 commit comments

Comments
 (0)