EFCore自动迁移

栏目: ASP.NET · 发布时间: 7年前

内容简介:Gets all migrations that are defined in the assembly but haven't been applied to the target database.

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.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

你必须知道的495个C语言问题

你必须知道的495个C语言问题

Steve Summit / 孙云、朱群英 / 人民邮电出版社 / 2009-2 / 45.00元

“本书是Summit以及C FAQ在线列表的许多参与者多年心血的结晶,是C语言界最为珍贵的财富之一。我向所有C语言程序员推荐本书。” ——Francis Glassborow,著名C/C++专家,ACCU(C/C++用户协会)前主席 “本书清晰阐明了Kernighan与Ritchie《The C programming Language》一书中许多简略的地方,而且精彩地总结了C语言编程......一起来看看 《你必须知道的495个C语言问题》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具