TrackableEntities / EntityFrameworkCore.Scaffolding.Handlebars

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

Skip InverseProperty and ForeignKey Annotations generation with Virtualized Many To Many Table. #240

Closed mwmccallum closed 8 months ago

mwmccallum commented 9 months ago

When scaffolding with EF7/8 Core, Many To Many tables with both simple and complex keys, but no non-key properties are no longer generates a real physical class for the Many To Many table.

When using Data Annotations currently the InverseProperty and ForeignKey Annotations are generated, which result in compile errors as there is no physical class for the table to be references with nameof() calls.

EF has an extension for IEntityType, IsSimpleManyToManyJoinEntityType which only checks if there is single PK from each table in the intersection table. This component has a complex IsManyToManyJoinEntityType which checks to see if only key fields exist in the association table.

IsManyToManyJoinEntityType is a private static method currently in HbsCSharpDbContextGenerator.cs. This needs to be made into an extension that could be used in HbsCSharpDbContextGenerator and HbsCSharpEntityTypeGenerator.

With an extension IsManyToManyJoinEntityType method, now we can test inside of HbsCSharpEntityTypeGenerator when preparing to call GenerateForeignKeyAttribute and GenerateInversePropertyAttribute, that these are not executed if IsManyToManyJoinEntityType returns true.

In the fix for this, IsManyToManyJoinEntityType will be moved from HbsCSharpDbContextGenerator.cs to EntityTypeExtensions.cs. Then HbsCSharpEntityTypeGenerator.GenerateNavigationDataAnnotations entityType.IsManyToManyJoinEntityType() will be tested to see if GenerateForeignKeyAttribute and GenerateInversePropertyAttribute should be executed.

Thanks, Mike