简体   繁体   中英

Adding EF Core Migrations to an existing database, while still enabling creation of the database from scratch

Last year, I rewrote a legacy application with.Net Core and EF Core, but elected not to add migrations at the time due to other limiting factors. The time has finally come where the new application can operate as the "single source of truth" for schema changes, but I'm at a bit of a loss as to the best way to move forward.

My end-goal is to have migrations that can scaffold out the entire existing database from nothing (minus the data contained within the non-lookup tables). Unfortunately, the most viable solution I've come up with so far is to build my migrations against a new, blank database. Then once the initial migration is created that matches the state of the current database, I would be able to copy over the __EFMigrationsHistory from the newly created database to the old one.

Alternatively, I can scaffold out a blank initial migration, and I could attempt to add logic in that migration to create the database from a SQL file if it did not exist.


Neither solution seems particularly "good". Aside from tools like FluentMigrator , are there any EF Core-centric approaches that can simplify creating migrations for an existing database that will need to be recreated for tests?

I had a similar issue when I wanted to squash all the existing migrations of the past 5 years (because it took forever to create a new instance). Here's how I did it:

  1. Remove all migrations from your code, including any DbContextModelSnapshot.cs
  2. Scaffold an initial migration: it will contain everything to create a new DB instance
  3. Scaffold another migration, dedicated to seed the initial data (that's optional if you don't need to seed data on your newly created instance). The goal is to isolate the seed from the SQL structure.
  4. Commit your changes
  5. Keep the migrations, but remove the bodies of the Up and Down methods; the goal is to trick EF Core into thinking it applied those migrations
  6. Update your existing instances with those empty migrations: nothing will be done, but the __EFMigrationsHistory table will contain them and ignore them in the future
  7. Revert your changes, to restore the bodies of the migrations

With all those steps, you can now update your existing instances with any future migrations, yet also recreate new instances from scratch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM