.NET Core database model changes in production

不想你离开。 提交于 2019-12-06 19:42:28

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!