MigrateAsync after using EnsureCreatedAsync

asp.net-core-mvc c# entity-framework-core


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?

6/17/2019 3:07:29 PM

Popular Answer

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!

6/21/2019 7:47:25 AM

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