Skip to content

DataAnnotation: Usage of nameof in ForeignKeyAttribute/InversePropertyAttribute #107

@codingdna2

Description

@codingdna2

Hi, first of all thanks for the outstanding project!

I was comparing the output of this project with EF Core 3.1 and I see you're not using nameof in ForeignKeyAttribute/InversePropertyAttribute generation.

I did this simple modification to HbsCSharpEntityTypeGenerator.cs:

private void GenerateForeignKeyAttribute(INavigation navigation)
{
    if (navigation.IsDependentToPrincipal())
    {
        if (navigation.ForeignKey.PrincipalKey.IsPrimaryKey())
        {
            var foreignKeyAttribute = new AttributeWriter(nameof(ForeignKeyAttribute));

            if (navigation.ForeignKey.Properties.Count > 1)
            {
                foreignKeyAttribute.AddParameter(
                        CSharpHelper.Literal(
                            string.Join(",", navigation.ForeignKey.Properties.Select(p => p.Name))));
            }
            else
            { 
                foreignKeyAttribute.AddParameter($"nameof({navigation.ForeignKey.Properties.First().Name})");
            }

            NavPropertyAnnotations.Add(new Dictionary<string, object>
            {
                { "nav-property-annotation", foreignKeyAttribute.ToString() },
            });
        }
    }
}

private void GenerateInversePropertyAttribute(INavigation navigation)
{
    if (navigation.ForeignKey.PrincipalKey.IsPrimaryKey())
    {
        var inverseNavigation = navigation.FindInverse();

        if (inverseNavigation != null)
        {
            var inversePropertyAttribute = new AttributeWriter(nameof(InversePropertyAttribute));

            inversePropertyAttribute.AddParameter(
                !navigation.DeclaringEntityType.GetPropertiesAndNavigations().Any(
                        m => m.Name == inverseNavigation.DeclaringEntityType.Name)
                    ? $"nameof({inverseNavigation.DeclaringEntityType.Name}.{inverseNavigation.Name})"
                    : CSharpHelper.Literal(inverseNavigation.Name));

            NavPropertyAnnotations.Add(new Dictionary<string, object>
            {
                { "nav-property-annotation", inversePropertyAttribute.ToString() },
            });
        }
    }
}

I'll try to provide a PR later.
Kind Regards

EDIT: Aligned code with CSharpEntityTypeGenerator.cs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions