TrackableEntities / EntityFrameworkCore.Scaffolding.Handlebars

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

Multiple Schema scaffold not setting HasForeignKey in HbsCSharpDbContextGenerator with correct Schema name. #238

Closed mwmccallum closed 6 months ago

mwmccallum commented 6 months ago

When using multiple schemas, where a there is a FK reference between the schemas, the .HasForeignKey<> has the schema of the "foreignKey" property and not that of the "entityType" property.

Example DB Schema: ` CREATE TABLE dbo.activity ( acti_number INT NOT NULL , acti_desc VARCHAR(50) , CONSTRAINT Xpk_acti PRIMARY KEY CLUSTERED ( acti_number ASC ) );

CREATE TABLE api.activity_test_queue ( actq_number INT NOT NULL , actq_acti_number INT NOT NULL , CONSTRAINT Xpk_actq PRIMARY KEY CLUSTERED ( actq_number ASC ), CONSTRAINT Ractq_acti_number FOREIGN KEY(actq_acti_number) REFERENCES dbo.activity (acti_number) );

CREATE UNIQUE NONCLUSTERED INDEX Xfk_actq_acti ON api.activity_test_queue ( actq_acti_number ASC ); `

Should generate following FK entry in Entity "api.activity_test_queue" ` modelBuilder.Entity(entity => { .... Eliminated all other for brevity

entity.HasOne(d => d.actq_acti_numberNavigation) .WithOne(p => p.activity_test_queue) .HasForeignKey(d => d.actq_acti_number) .HasConstraintName("Ractq_acti_number"); }); What is actually being generated: modelBuilder.Entity(entity => { .... Eliminated all other for brevity

entity.HasOne(d => d.actq_acti_numberNavigation) .WithOne(p => p.activity_test_queue) .HasForeignKey(d => d.actq_acti_number) .HasConstraintName("Ractq_acti_number"); }); `

This is due to use of "foreignKey.PrincipalEntityType" instead of "entityType" to get "".

By changing from: ` lines.Add( $".{nameof(ReferenceReferenceBuilder.HasForeignKey)}"

`

To: ` lines.Add( $".{nameof(ReferenceReferenceBuilder.HasForeignKey)}"

`

Resolves this issue. Unfortunately the NorthwindTestDB (NorthwindsSlim) doesn't have multiple schemas to build a test case for this. However, I did run in on our multiple schema database and it did generate the proper DBContext entry as noted above.

This could be an originating bug from EFCore where "foreignKey.PrincipalEntityType" doesn't hold the schema for the Principal value but that of the Foreign value. But the above implementation resolves this issue.

Thanks, Mike

mwmccallum commented 6 months ago

Also added stop to remove annotation "RelationalAnnotationNames.DefaultValueSql" when "RelationalAnnotationNames.DefaultValue" is removed.

mwmccallum commented 6 months ago

Correction for #236 allowed all test cases to run correction. Prior to this correction, the tests cases failed where DBContext was generated as it was missing the additional annotations.