TrackableEntities / EntityFrameworkCore.Scaffolding.Handlebars

Scaffold EF Core models using Handlebars templates.
MIT License
208 stars 53 forks source link

DataAnnotation: Usage of nameof in ForeignKeyAttribute/InversePropertyAttribute #107

Closed codingdna2 closed 4 years ago

codingdna2 commented 4 years ago

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

tonysneed commented 4 years ago

Very good catch. Thank you also for the PR! I will have a look.