Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consolidating EF migrations into new InitialCreate

I have been using EF migrations for some time now and have more than 100 migration files in my project. I would like to consolidate these into a single migration before moving forward - ie I want to replace the existing InitialCreate migration with a new version that takes all my subsequent changes into account so I can then delete all the other migration files.

I do this very easily if I am not concerned with losing all the data in the DB, but I am.

How can I achieve this whilst keeping all data intact and also retaining the ability to recreate the database from scratch (without data) by just running Update-Database (which I believe is not possible using the approach outlined by Julie Lerman)?

like image 509
Paul Hiles Avatar asked Nov 14 '12 13:11

Paul Hiles


People also ask

Does ef core support automatic migration?

Entity Framework introduced automated migration so that you don't have to process database migration manually for each change you make in your domain classes. The automated migrations can be implemented by executing the enable-migrations command in the Package Manager Console.


1 Answers

Consider reading this nice article from Rick Strahl : https://weblog.west-wind.com/posts/2016/jan/13/resetting-entity-framework-migrations-to-a-clean-slate

Basically the solution is not trivial and needs more than just reseting all the migrations into one because you have two scenarios that needs to fit in ONE migration class:

  • Create a new database => the migration class should contain every table creation
  • My database is already up to date => I need an empty migration class

Solution: The idea of this process is basically this: The database and the EF schema are up to date and just the way you want it, so we are going to remove the existing migrations and create a new initial migration.

In summary, the steps to do this are:

  • Remove the _MigrationHistory table from the Database
  • Remove the individual migration files in your project's Migrations folder
  • Enable-Migrations in Package Manager Console
  • Add-migration Initial in PMC
  • Comment out the code inside of the Up method in the Initial Migration
  • Update-database in PMC (does nothing but creates Migration Entry) Remove comments in the Initial method You've now essentially reset the schema to the latest version.
  • once the commented out migration has been executed on the desired database, uncomment the migration code
like image 58
Michael Avatar answered Oct 17 '22 09:10

Michael