Skip to content

Add support for composite foreign keys to Parsing/MappingVisitor #620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 16, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 47 additions & 3 deletions src/EntityFrameworkCore.Generator.Core/Parsing/MappingVisitor.cs
Original file line number Diff line number Diff line change
@@ -116,6 +116,46 @@ private string ParseLambaExpression(InvocationExpressionSyntax node)
return propertyName;
}

private List<string> ParseLambdaExpressionForAnonymousObject(InvocationExpressionSyntax node)
{
if (node == null)
return null;

var lambdaExpression = node
.ArgumentList
.DescendantNodes()
.OfType<LambdaExpressionSyntax>()
.FirstOrDefault();

if (lambdaExpression == null)
return null;

var anonymousObject = lambdaExpression
.ChildNodes()
.OfType<AnonymousObjectCreationExpressionSyntax>()
.FirstOrDefault();

if (anonymousObject == null)
return null;

var propertyNames = anonymousObject
.ChildNodes()
.OfType<AnonymousObjectMemberDeclaratorSyntax>()
.Select(declarator => declarator
.ChildNodes()
.OfType<MemberAccessExpressionSyntax>()
.FirstOrDefault())
.Where(memberAccess => memberAccess != null)
.Select(memberAccess => memberAccess
.ChildNodes()
.OfType<IdentifierNameSyntax>()
.Select(identifier => identifier.Identifier.ValueText)
.LastOrDefault())
.Where(propertyName => propertyName != null)
.ToList();

return propertyNames;
}

private void ParseHasOne(InvocationExpressionSyntax node)
{
@@ -153,13 +193,17 @@ private void ParseForeignKey(InvocationExpressionSyntax node)
if (node == null || ParsedEntity == null)
return;

var propertyName = ParseLambaExpression(node);
List<string> propertyNames = null;
if (ParseLambaExpression(node) is string propertyName && !string.IsNullOrEmpty(propertyName))
propertyNames = new List<string> { propertyName };
else
propertyNames = ParseLambdaExpressionForAnonymousObject(node);

if (string.IsNullOrEmpty(propertyName))
if (propertyNames == null)
return;

_currentRelationship ??= new ParsedRelationship();
_currentRelationship.Properties.Add(propertyName);
_currentRelationship.Properties.AddRange(propertyNames);
}

private void ParseConstraintName(InvocationExpressionSyntax node)