SQL surrogate table are not generated anymore by scaffolding tool after upgrade to .NET 6

45 views Asked by At

I have a SQL surrogate table defined as follows:

CREATE TABLE [dbo].[Blah] 
(
    [FooID] INT NOT NULL,
    [ClientID] INT NOT NULL,

    CONSTRAINT [PK_Blah] 
        PRIMARY KEY CLUSTERED ([FooID] ASC, [ClientID] ASC),
    CONSTRAINT [FK_Blah_Foo] 
        FOREIGN KEY ([FooID]) REFERENCES [dbo].[Foo] ([FooID]) 
                ON DELETE CASCADE,
    CONSTRAINT [FK_Blah_Client] 
        FOREIGN KEY ([ClientID]) REFERENCES [dbo].[Client] ([ClientID]) 
                ON DELETE CASCADE
);

I have noticed that after upgrading from .NET Core version 3 to 6, the db-first scaffolding tool changed its behavior and stopped generating the surrogate tables. I have done some research and checked several options on how to force EF Core to generate the Blah table.

1) One of the options is to use the -Tables Blah parameter in the Scaffold-DbContext command. However, this only generates the Blah table, and all the others are gone, which means that I would need to list all the existing SQL tables in this command, which is not generic at all and has many disadvantages.

Scaffold-DbContext "..." Microsoft.EntityFrameworkCore.SqlServer 
    -OutputDir Entities -ContextDir . -DataAnnotations 
    -UseDatabaseNames -Context AuthorisationContext -Force 
    -NoOnConfiguring -NoPluralize -Tables Blah

2) The other solution I found is that I can just run the above scaffolding command to generate the Blah entity class, revert all the changes on the DbContext, and add the Blah definition into the MyDbContext partial class that I created manually for such needs where you need to extend the dbContext manually

public partial class MyDbContext : DbContext
{
    public virtual DbSet<Blah> Blah { get; set; }
    
    //...
}

To be honest, for now, I see option 2) as the only solution for me. However, I wanted to check if there is any other nice way to achieve what I want purely by modifying the scaffolding command and it's params? Cheers.

Edit I also played with .NET 7 and I'm getting similar results.

1

There are 1 answers

1
Boosa Sandeep On

When we have only foreign key constraints, EF DB scaffolding will ignore those tables. To fix this issue, we can add an Identity column to the existing table and then run the scaffolding command.