.NET Core database model changes in production

.net-core asp.net-core entity-framework-core


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.

7/24/2017 5:40:12 PM

Accepted Answer

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...

  1. restore your code (i.e. going back to an older revision in your VCS)
  2. create a table layout based on it (running Add-Migration InitialVersion or dotnet ef migrations add InitialVersion followed by Update-Database or dotnet ef database update
  3. reapply your model changes (going back to your current revision in VCS, but keeping the files in the Migration folder)
  4. run Add-Migration ModelUpdateV2 or dotnet ef migrations add ModelUpdateV2
  5. run Script-Migration (Thanks @Smit!) or dotnet ef migrations script. This will generate an SQL command for applying the changes to the schema

From now on you have two options:

  1. 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 call context.Database.MigrateAsync() within your Startup.cs).

    From now on you should be able to use migrations in future

  2. 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.

7/25/2017 11:11:23 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow