2

I have an asp.net core mvc site in production. The DbInitializer was using this code: await context.Database.EnsureCreatedAsync()

Now I found out that a migration was not being applied and I've seen this:

In addition, the database that is created cannot be later updated using migrations.

I've changed code to await context.Database.MigrateAsync() but no migrations are being applied and in my database dbo.__EFMigrationsHistory I don't see any records.

note: my solution has already 4 migration classes in the Migrations folder, but they are added in MigrationHistory. 3 of them are applied because I had once recreated the database (still using ensurecreated). The last migration is not applied, as I now didn't recreate the database as it contains data and migrations are not applied now because I used before "EnsureCreatedAsync".

How can I now apply and start using migrations in my existing database without losing any of my database data?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
juFo
  • 17,849
  • 10
  • 105
  • 142
  • 3
    See: https://stackoverflow.com/a/38241900/7897176 Notably, if you originally called `EnsureCreated`, "the database that is created cannot later be updated using migrations" – Valuator Jun 17 '19 at 15:10

1 Answers1

0

Found out it is not possible (hopefully I'm wrong).

  1. created a backup of the database using SSMS.
  2. generated a script of the database from the tables containing data. So that I have all the insert statements in an .sql file.
  3. deleted the database, created a new empty one, made sure the security (assign database user) was ok
  4. visual studio, deleted all migrations from solutions which were not applied.
  5. removed the seeding data from my solution (so that it would not later conflict with my insert statements in the .sql script to put data back).
  6. enabled migrations again by doing Add-Migration Initial
  7. Tried my migrations with Update-Database on my development/debug database
  8. Published the website and made it available on the webserver.
  9. started the website in IIS and verified in SSMS that all my tables were correctly created and that _migrationhistory contained my Initial migration
  10. opened SSMS and run my query from .sql having all the INSERT statements --> all data was added again.

now my (new) database is having Migrations enabled. hooray for Microsoft!

juFo
  • 17,849
  • 10
  • 105
  • 142