Loading

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.

posted @ 2019-05-14 21:18  kasnti  阅读(3263)  评论(1编辑  收藏  举报