I follow code first approach to generate my databases by EFCore. Now during development one of my models changed. How can I update the corresponding database tables on a live system at one of our customers? I do not want to dump or delete any data of course.
I'm still on .NET Core 1.1.0.
I fear you'll have to swallow the pill then.
Database.EnsureCreated()
is only useful for developing, where you don't have to preserve data. If you have to preserve data or change the table schema, you have to use migrations or database scaffolding (create models from Database schema).In any case, do a backup of the production data, before applying/attempting following steps and try it out upfront on a staging server.
One touchy option would be...
Add-Migration InitialVersion
ordotnet ef migrations add InitialVersion
followed byUpdate-Database
ordotnet ef database update
Add-Migration ModelUpdateV2
ordotnet ef migrations add ModelUpdateV2
Script-Migration
(Thanks @Smit!) ordotnet ef migrations script
. This will generate an SQL command for applying the changes to the schemaFrom now on you have two options:
Look for a
__EFMigrationHistory
table within your database on the development database. It should contain one entry with your initial migration name. Export this table into your production system. Then you application should apply the migrations on the next start (when you callcontext.Database.MigrateAsync()
within your Startup.cs).From now on you should be able to use migrations in future
Just execute the migration script from above, without copying over
__EFMigrationHistory
, but then you'll have to repeat the steps above.The other option is, to always create the models from the database (see
dotnet ef dbcontext scaffold
command (see EF Core Docs) do create models from database schema in future.Then every time you change the table, you have to create your own SQL for migration and apply that before or while deploying the application.