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.
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.
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!
You need to do a migration DO NOT rescaffold or you will lose any work done on the models, such as data validations.
If we have customize in dbcontext
class E.g. add LoggerFactory
and then after we are using ('Scaffold-DbContext "Server=(localdb)\v11.0;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force')
. this command then all customize changes will be lost.