EFCore自动迁移

2019/05/14,EFCore 2.2.4

有两种方式:

1.使用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.

2.使用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.

转载于:https://www.cnblogs.com/kasnti/p/10864668.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值