Consolidating EF migrations into new InitialCreate

后端 未结 4 1618
轮回少年
轮回少年 2021-02-01 01:18

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 f

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 01:55

    Removing all migrations or regenerating them has drawbacks so we took an approach we merged all older migrations.

    It require a bit of scripting. You read about the details here https://www.bokio.se/engineering-blog/how-to-squash-ef-core-migrations/ and see the scripts here https://github.com/bokio/EFCoreTools/tree/main/MigrationSquasher

    The basic is the following steps though (copied from the blog post):

    Overview of our approach

    1. Create a new fresh database from the old migrations (We will use this for comparison later)
    2. Find a suitable target migration to be the new initial (We picked one about 3 months old)
    3. Write a script to merge the Up() methods of all earlier migrations into the Up() method of a new migration. We ignored Down() because we don't use it for old migrations.
    4. Generate this migration and add it to the project. In our case we called it 20200730130157_SquashedMigrations1.cs. We used the snapshot from the target migration we had picked.
    5. Generate a 2nd prep migration that inserts into the migrations history that 20200730130157_SquashedMigrations1.cs has already run. We called this 20200730130156_SquashedMigrations1_prep.cs. Note the slightly smaller timestamp on that one to make sure it runs before the real migrations.
    6. Delete the old migrations
    7. Point our config to a new database and run the migrations.
    8. Compare that the schema we generate is equal using the Sql Schema Compare in Visual Studio.
    9. Work through the issues until we have equal schemas. This part is a bit complicated but I will get back to it.
    10. Merge and

提交回复
热议问题