2019/05/14,EntityFrameworkCore 2.2.4
有兩種方式:
使用Migrate()方法
if (DbContext.Database.GetPendingMigrations().Any())
{
DbContext.Database.Migrate(); //執行遷移
}
Migrate()
方法使用前需在程序包管理控制台執行Add-migration
遷移命令。之后程序每次啟動,GetPendingMigrations()
都會去檢測是否有待遷移內容,有的話,自動應用遷移。
GetPendingMigrations方法官方文檔說明
Gets all migrations that are defined in the assembly but haven't been applied to the target database.
使用EnsureCreated()方法
//如果成功創建了數據庫,則返回true
DbContext.Database.EnsureCreated()
此方法不需要先執行Add-migration
遷移命令,如果數據庫不存在,則自動創建並返回true
。
如果已經創建了數據庫后,又改動了實體Model和之前的庫存在沖突,要注意刪庫讓它自動重建,否則會報錯。
EnsureCreated方法官方文檔說明
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.