问题
By VS 2019, I created an API project (database first), everything it's working well, now I made some changes in the database like add new tables and some property and modify data type for others and so on.., the question is how to update models to match the database in SQL?
this is a screenshot for my project:
回答1:
Try to recreate your models via Scaffold-DbContext with "Force" param.
Scaffold-DbContext "Data Source=yoursource;Initial Catalog=yourdb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Model -Force
回答2:
From the document:
https://docs.microsoft.com/en-us/ef/ef6/modeling/designer/workflows/database-first
The first step is to make some changes to the database schema. We’re going to add a Users table to the schema.
- Right-click on the database in Server Explorer and select New Query
- Copy the following SQL into the new query, then right-click on the query and select Execute
CREATE TABLE [dbo].[Users]
(
[Username] NVARCHAR(50) NOT NULL PRIMARY KEY,
[DisplayName] NVARCHAR(MAX) NULL
)
Now that the schema is updated, it’s time to update the model with those changes.
- Right-click on an empty spot of your model in the EF Designer and select ‘Update Model from Database…’, this will launch the Update Wizard
On the Add tab of the Update Wizard check the box next to Tables, this indicates that we want to add any new tables from the schema. The Refresh tab shows any existing tables in the model that will be checked for changes during the update. The Delete tabs show any tables that have been removed from the schema and will also be removed from the model as part of the update. The information on these two tabs is automatically detected and is provided for informational purposes only, you cannot change any settings.
Click Finish on the Update Wizard
The model is now updated to include a new User entity that maps to the Users table we added to the database.
回答3:
Hi I am Considering you are using EFCore, please confirm !!
As per available information over internet
EF core for DB first ( from db to EF ) approach to Modify new/existing entity
you need to follow steps as:
- EF model require to run Scaffold with flag Force
EF model require to run Scaffold with flag Force this will remove all your local changes in model (for me it was IdentityDBContext and override identityUser changes)
after run the all your model migration
running all migration will bring everything in sync bw EF and DB
now you need to do the local changaes again over solution ( for me update IdentityDBContext and override identityUser changes back as it was before db changes )
- also as per below answer please notice EDMX object is not available yet, anyone has any clue then please share here.
来源:https://stackoverflow.com/questions/59474928/how-to-update-models-in-vs-2019-from-database-in-entity-framework-in-asp-net-cor