EFCore自動遷移
EFCore自動遷移
2019/05/14,EFCore 2.2.4
有兩種方式:
1.使用Migrate()方法
if (DbContext.Database.GetPendingMigrations().Any()) { DbContext.Database.Migrate(); //執行遷移 }
Migrate()
方法使用前需在程式包管理控制檯執行Add-migration
遷移命令。之後程式每次啟動,GetPendingMigrations()
都會去檢測是否有待遷移內容,有的話,自動應用遷移。
Gets all migrations that are defined in the assembly but haven't been applied to the target database.
2.使用EnsureCreated()方法
//如果成功建立了資料庫,則返回true DbContext.Database.EnsureCreated()
此方法不需要先執行Add-migration
遷移命令,如果資料庫不存在,則自動建立並返回true
。
如果已經建立了資料庫後,又改動了實體Model和之前的庫存在衝突,要注意刪庫讓它自動重建,否則會報錯。
Ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created. If the database exists, then no effort is made to ensure it is compatible with the model for this context.