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