Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the model when using database first approach

I used EntityFramework Core database first to create model as illustrated in the EF Core documentation

But I don't know how to update the model when the database has been edit.

like image 369
witson Avatar asked Aug 03 '16 09:08

witson


People also ask

How do you update a model in database first approach?

Right-click anywhere on the design surface, and select Update Model from Database. In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish. After the update process is finished, the database diagram includes the new MiddleName property.


3 Answers

You can re-scaffold the model by running the command that you originally ran with the -Force option added. That will result in the contents of the specified folder being over-written. Using the Package Manager Console example from the EF Core docs, the revised command becomes:

Scaffold-DbContext "Server=(localdb)\v11.0;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force

Alternatively, if you are using CLI commands, it becomes:

dotnet ef dbcontext scaffold "Server=(localdb)\v11.0;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -f

However, you should consider using Migrations to keep your model and database schema in sync with each other. That way you make changes to the model and then propagate them to the database.

like image 197
Mike Brind Avatar answered Oct 12 '22 15:10

Mike Brind


Additional Tip

If you are going to update the models from time to time, here's a convenient way to simplify the process.

Head over to menu Tools > External Tools, and then Add a new menu and fill in the following entries:


Title:

Update DbContext

Command:

dotnet.exe

Arguments:

ef dbcontext scaffold "your-connection-string" Microsoft.EntityFrameworkCore.SqlServer --output-dir=Models --force

Initial directory:

$(ProjectDir)

Then optionally tick "Use Output window", hit Apply and OK.

When you go to Tools again, this new menu should be there and ready for reuse, in just a click of a button!

like image 21
Yom T. Avatar answered Oct 12 '22 16:10

Yom T.


You need to do a migration DO NOT rescaffold or you will lose any work done on the models, such as data validations.

like image 8
JD Patton Avatar answered Oct 12 '22 14:10

JD Patton