I've scaffolded a few tables in a C# project. Now I need to scaffold a new table. I don't want to re-scaffold the existed ones because there were some changes.
Scaffold-DbContext "Server=...;Database=...;...;" Microsoft.EntityFrameworkCore.SqlServer `
-OutputDir Models -Tables newTable
The command will get the following error.
The following file(s) already exist in directory C:\Users....\Models: myContext.cs,newTable.cs. Use the Force flag to overwrite these files.
Using -Force
will overwrite the existed code for the existed tables.
I wish there were a built-in way to add entities and update an existing context, but there doesn't seem to be. I overcame this by using the --context
option in the package manager console and just gave it a temporary name, e.g. --context TempContext
. This worked and generated the new table and the temp context. Then I just copied the public virtual DbSet<NewEntityType> NewEntityType { get; set; }
property and the modelBuilder.Entity<NewEntityType>(entity =>
block from the OnModelCreating
method in the temp context to my existing one. After that, I deleted the temp context. It's pretty straightforward.
It will help you to change existing DbContext file.
If you have created a new table then New Class(entities) will create in your Models folder and if you drop existing tables then it will remove class(entities) in your Models folder.
For Package Manager Console
BloggingContext is my own database context file, You have to change by your name.
Use commands in Package Manager Console
Scaffold-DbContext "Server=SERVER_NAME; Database=DATABASE_NAME; User Id=USER_ID; Password=PASWWORD;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -context "BloggingContext" -Force
One dialog will open. Select appropriate option.
I choose "Yes to All"
and remove OnConfiguring() from BloggingContext.cs file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With