简体   繁体   中英

Merge migrations in entity-framework-core

Is it possible to merge all migrations files into one ?

I created initial migration.

dotnet ef migrations add InitialMigration

Source

When ever I have some model change I create new migration update.

But now I have too many migration update files. Is ti possible to merge all migration files to one ?

Off course drop database is not an option, I have to preserve data !

EF 6.X has a option IgnoreChanges . That is the perfect fit for your scenario. But unfortunately it is not a feature available in EF core.

But there is a workaround.

Step 1 : Delete all the migration scripts in the Migrations folder.

Step 2 : In the package manager console : run

PM> Add-Migration InitialCreate

Step 3 : Delete both Up() and Down() methods code. Before you do this, keep those methods saved elsewhere as we will need them again in step 5.

Step 4 : run:

 PM> Update-Database

It'll insert a new record into __EFMigrationsHistory table.

Step 5 : After that fill the above migration script's (ie .._InitialCreate ) Up() and Down() method from the content kept in a safe place from Step 3 .

That is it. Now you have only 1 migration file :)

Note : EF core with Package manager console (PM) : Package Manager Console

One way to do that is removing all migration files physically and adding new one. If your migrations are in "Migrations" folder, you can simply delete it, otherwise you need to delete your "ModelSnapshot" file too. I think this approach can solve your issue.

When you want to merge not all but N last migrations, the protocol is not the same:

  1. Revert N last migrations, one by one , each with the 2 following commands:
    • dotnet ef database update NameOfTheLastMigration
    • dotnet ef migrations remove
  2. Apply reverts to database:
    • dotnet ef database update
  3. Create the "merge" migration:
    • dotnet ef migrations add NameOfTheMergeMigration

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