天天看點

EntityFrameworkCore自動遷移

EntityFrameworkCore自動遷移

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.

繼續閱讀