場景描述:項目中存在兩個遷移 Teacher
和 TeachingPlan
,TeachingPlan
在 Teacher
之后創建,並且已經執行 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
可以將數據庫更新到任何一個指定遷移時的架構。