R4ND3LL / EntityFrameworkRuler

Automate the customization of the Entity Framework Reverse Engineered model, including EDMX support for EF6 upgrades.
MIT License
20 stars 5 forks source link

Template problems with inheritance #18

Closed jdanielpa closed 1 year ago

jdanielpa commented 1 year ago

I cannot figure out how to remove the HasKey line from OnModelCreating for classes that inherit. Here is an example:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("dbo");

        modelBuilder.Entity<ArcAutoRadius>(entity =>
        {
            //entity.HasKey(e => e.EntryExitID);
            entity.ToTable("BaseEntryExit");

            entity.Property(e => e.EntryExitClassName)

ArcAutoRadius inherits BaseEntryExit. Scaffolding still adds the entity.HasKey line which then throws an error on calls to the database. If I comment out the entity.HasKey line then the calls to the database work.

Can you tell me if there is a way to remove the entity.HasKey line using the templates?

Thanks!

R4ND3LL commented 1 year ago

Just change T4 line

        var key = EntityType.FindPrimaryKey();
        if (key != null)

to

        var key = EntityType.FindPrimaryKey();
        if (key != null && (EntityType.BaseType == null || key.Properties.Any(o=> o.DeclaringEntityType == EntityType)))

I've applied the same change to my code base v1.2.14

Note, I can now scaffold and run your context. It all appears to work fine on v1.2.14

jdanielpa commented 1 year ago

I changed the line in my template to:

        var key = entityType.FindPrimaryKey();
        if (key != null && (EntityType.BaseType == null || key.Properties.Any(o=> o.DeclaringEntityType == EntityType)))

but I get an error scaffolding:

DbContext rule file written to OptiCAMEntities-rules.json Updated OptiCamEntities-rules.json in 32ms CodeTemplates\EFCore\DbContext.t4(131,29) : error CS0103: The name 'EntityType' does not exist in the current context

CodeTemplates\EFCore\DbContext.t4(131,108) : error CS0103: The name 'EntityType' does not exist in the current context

Any ideas?

jdanielpa commented 1 year ago

Never mind - typo! That fixed it.

R4ND3LL commented 1 year ago

FYI, one more adjustment made today (v1.2.15) for an issue affecting scaffolding with inheritance. just in case you hit an exception.