Let's say I'm a new developer in a company. So there is already an existing database for the project. To work on the project, obviously I need to scaffold the existing database(database first approach), which can generate model classes for me to work on.
So I start to work on the project and want to add a new column to a table, so I add a new property on the model class then I want to apply this change in the database. So I switch back to code first approach by adding a new migration and update the database.
But the problem is, if I add a new migration, EF will include all the data model classes in the migration's UP method to create all the corresponding tables in the database because EF think all the model classes are newly added by me. So how can I only get the table updated by adding a new column without re-create all other tables?
1) Reverse engineer the models and db context from the existing database. Follow this link for that, https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db
2) Now you have the models and db context. Your data access should work fine with the new context, except migrations.
3) Now that you already have the database and tables created, you need to tweak your DB to pretend that current schema is created using migrations.
3.1) First create the Initial Migration Add-Migration IntitialCreate
. It will have code to create the database up to current level.
3.2) Now you should have to manually create __MigrationHistory table and manually insert IntialMigration to the table, so that it wont try to apply it again. If you find hard to do this manually, there is trick.
Create a new database using you current migrations by just changing the Database name in the connection string and executing update-database
. In the new database created __MigrationHistory table should be created with InitialCreate migration already applied. Generate a create script along with data and execute that in the original database.
4) Now you can do the rest of the changes to the model, create new migrations apply them as usual.
来源:https://stackoverflow.com/questions/57641888/how-to-combine-both-of-code-first-and-database-first-approaches