Why do we need to do that?

In case you ruined your code or you have too many migrations and caused your editor slow, you may want to reset all migrations.

However, deleting all migrations directly in your code will cause database update fail. So I will talk about my solution about how to consolidate all migrations without deleting any data.

The following steps only suitable for code-first EF Core. And I can't ensure your data will not be lost. Before starting, I strongly suggest you back up your data first.

  • Step 1: Delete all *.cs files under your Migrations folder.
  • Step 2: Delete all items in _EFMIgrationHistory table in database. Like: delete from table _EFMIgrationHistory (Caution: Is to delete, not drop)
  • Step 3: Create a new migration like: dotnet ef migrations add Init
  • Step 4: Comment all content in the Up method and Down method in the generated class 20XXXXX_Init.cs by the previous step.
  • Step 5: Update your database with the current status of your application. This step will not change your database but only create an item in your _EFMigrationHistory table. This will record a history in the database that Init migration is already applied to the database.
  • Step 6: Uncomment the Up and Down method in your C# file.
  • Step 7: Check in to your version control if you have.
  • Step 8: Re-run dotnet ef database update. This may show that everything is already latest. And that is what we expected.
  • Step 9: Start your app. And your app runs just fine.

If you have other environments using other databases, you need to do the following steps For each databases!

  • Step 10: Check out the latest code you pushed in step 7.
  • Step 11: Delete all items in _EFMIgrationHistory table in database. Like: delete from table _EFMIgrationHistory (Caution: Is to delete, not drop)
  • Step 12: Comment all content in the Up method and Down method in the generated class 20XXXXX_Init.cs by the step 3.
  • Step 13: Update your database with the current status of your application. This step will not change your database but only create an item in your _EFMigrationHistory table. This will record a history in the database that Init migration is already applied to the database.
  • Step 14: Reset your code status to step 10. For example: git reset --hard HEAD
  • Step 15: Try to run your application.