EF Migrations: Rollback last applied migration?

后端 未结 15 1182
终归单人心
终归单人心 2020-12-02 03:39

This looks like a really common task, but I can\'t find an easy way to do it.

I want to undo the last applied migration. I would have expected a simple command, lik

15条回答
  •  眼角桃花
    2020-12-02 04:02

    I want to add some clarification to this thread:

    Update-Database -TargetMigration:"name_of_migration"
    

    What you are doing above is saying that you want to rollback all migrations UNTIL you're left with the migration specified. Thus, if you use GET-MIGRATIONS and you find that you have A, B, C, D, and E, then using this command will rollback E and D to get you to C:

    Update-Database -TargetMigration:"C"
    

    Also, unless anyone can comment to the contrary, I noticed that you can use an ordinal value and the short -Target switch (thus, -Target is the same as -TargetMigration). If you want to rollback all migrations and start over, you can use:

    Update-Database -Target:0
    

    0, above, would rollback even the FIRST migration (this is a destructive command--be sure you know what you're doing before you use it!)--something you cannot do if you use the syntax above that requires the name of the target migration (the name of the 0th migration doesn't exist before a migration is applied!). So in that case, you have to use the 0 (ordinal) value. Likewise, if you have applied migrations A, B, C, D, and E (in that order), then the ordinal 1 should refer to A, ordinal 2 should refer to B, and so on. So to rollback to B you could use either:

    Update-Database -TargetMigration:"B"
    

    or

    Update-Database -TargetMigration:2
    

    Edit October 2019:

    According to this related answer on a similar question, correct command is -Target for EF Core 1.1 while it is -Migration for EF Core 2.0.

提交回复
热议问题