EF Core 小技巧:迁移已经应用到数据库,如何进行迁移回退操作?

场景描述:项目中存在两个迁移 TeacherTeachingPlanTeachingPlanTeacher 之后创建,并且已经执行 dotnet ef database update 将新迁移应用到数据库。此时,因为实体修改,我们希望删除 TeachingPlan 迁移然后创建新的 TeachingPlan 迁移,该怎么办?

示例:查看迁移列表

dotnet ef migrations list
Build started...
Build succeeded.
20211026071835_Teacher
20211108141706_TeachingPlan

分析:直接移除 TeachingPlan 行不行?我们先试试。

示例:移除最后一个迁移

dotnet ef migrations remove
Build started...
Build succeeded.
The migration '20211108141706_TeachingPlan' has already been applied to the database. Revert it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration instead.

移除失败:迁移已经应用到数据库。如果该迁移已经应用于其他数据库,请考虑用一个新的迁移来恢复其变化。

根据错误提示,建议我们再创建一个新的迁移,比如:TeachingPlan_01 ,这样能够达到效果,但是不够简洁,存在多个作用相同的迁移。

重新梳理思路:在移除迁移之前,先将数据库恢复到数据迁移之前的状态。使用 dotnet ef database update [miagration_anme] 可以将数据库架构恢复到指定迁移时的状态。

示例:将数据库恢复到 Teacher

dotnet ef database update Teacher

然后移除 TeachingPlan 迁移

dotnet ef migrations remove

移除成功!此时迁移和数据库结构都恢复到 Teacher 状态,再重新创建迁移:

dotnet ef migrations add TeachingPlan

迁移回退任务完成!

小结:

  • 迁移具有前后连贯性,迁移和数据架构应保持一致性。应避免删除已应用到生产数据库的任何迁移。
  • dotnet ef migrations remove 不带参数,每执行一次,则移除最新创建的迁移。
  • dotnet ef database update 可以将数据库更新到任何一个指定迁移时的架构。
posted @ 2021-11-09 17:24  iEricLee  阅读(1039)  评论(1编辑  收藏  举报