Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaffold new tables and keep the existed ones?

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.

like image 535
ca9163d9 Avatar asked Jun 27 '17 20:06

ca9163d9


2 Answers

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.

like image 65
rory.ap Avatar answered Nov 15 '22 17:11

rory.ap


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.

like image 23
Pradip Rupareliya Avatar answered Nov 15 '22 16:11

Pradip Rupareliya