Entity Framework Core 2.0 使用代码进行自动迁移
一.前言
我们在使用EF进行开发的时候,肯定会遇到将迁移更新到生产数据库这个问题,前面写了一篇文章介绍了Entity Framework Core 2.0的入门使用,这里面介绍了使用命令生成迁移所需的SQL,然后更新到生产数据库的方法。这里还有另一种方法,就是利用EF Core自身所提供的方法来进行迁移。
二.API说明
这些方法都是DatabaseFacade的扩展方法,我们常使用的DbContext.Database就是DatabaseFacade类型。
GetMigrations获取所有迁移
/// <summary>
/// Gets all the migrations that are defined in the configured migrations assembly.
/// </summary>
public static IEnumerable<string> GetMigrations([NotNull] this DatabaseFacade databaseFacade)
GetPendingMigrations获取待迁移列表
/// <summary>
/// Gets all migrations that are defined in the assembly but haven't been applied to the target database.
/// </summary>
public static IEnumerable<string> GetPendingMigrations([NotNull] this DatabaseFacade databaseFacade)
GetAppliedMigrations获取执行了迁移的列表
/// <summary>
/// Gets all migrations that have been applied to the target database.
/// </summary>
public static IEnumerable<string> GetAppliedMigrations([NotNull] this DatabaseFacade databaseFacade)
Migrate执行迁移
/// <summary>
/// <para>
/// Applies any pending migrations for the context to the database. Will create the database
/// if it does not already exist.
/// </para>
/// <para>
/// Note that this API is mutually exclusive with DbContext.Database.EnsureCreated(). EnsureCreated does not use migrations
/// to create the database and therefore the database that is created cannot be later updated using migrations.
/// </para>
/// </summary>
/// <param name="databaseFacade"> The <see cref="T:Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade" /> for the context. </param>
public static void Migrate([NotNull] this DatabaseFacade databaseFacade)
三.实现自动迁移
我们可以利用上面的方法,让程序在启动的时候检查是否有待迁移,如果有那么执行迁移。这里以一个.NET Core 控制台应用程序作为示例:
1.定义一个检查迁移的方法
/// <summary>
/// 检查迁移
/// </summary>
/// <param name="db"></param>
static void CheckMigrations(BloggingContext db)
{
Console.WriteLine("Check Migrations");
//判断是否有待迁移
if (db.Database.GetPendingMigrations().Any())
{
Console.WriteLine("Migrating...");
//执行迁移
db.Database.Migrate();
Console.WriteLine("Migrated");
}
Console.WriteLine("Check Migrations Coomplete!");
}
2.在程序启动时调用
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
//检查迁移
CheckMigrations(db);
...
}
}
运行:

四.制作一个单独的迁移工具
上面的方法需要我们每次在应用程序启动的时候都去检查迁移,我们也可以单独制作一个控制台程序来进行迁移的更新,这样只要在更新迁移的时候放到服务器上执行一下就行 了。
我们在实际使用中,建议将EntityFrameWork Core单独作为一个项目
代码如下:
static void Main(string[] args)
{
Console.WriteLine("Entity Framework Core Migrate Start !");
Console.WriteLine("Get Pending Migrations...");
using (var db = new BloggingContext())
{
//获取所有待迁移
Console.WriteLine($"Pending Migrations:\n{string.Join('\n', db.Database.GetPendingMigrations().ToArray())}");
Console.WriteLine("Do you want to continue?(Y/N)");
if (Console.ReadLine().Trim().ToLower() == "n")
{
return;
}
Console.WriteLine("Migrating...");
try
{
//执行迁移
db.Database.Migrate();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
Console.WriteLine("Entity Framework Core Migrate Complete !");
Console.WriteLine("Press any key to exit !");
Console.ReadKey();
}
执行效果:

本文Demo:https://github.com/stulzq/EntityFramework-Core-Migrator
Entity Framework Core 2.0 使用代码进行自动迁移的更多相关文章
- Entity Framework Core 2.0 全局查询过滤器
不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://gunnarpeipman.com/2017/08/ef ...
- .Net Core 2.0生态(4):Entity Framework Core 2.0 特性介绍和使用指南
前言 这是.Net Core 2.0生态生态介绍的最后一篇,EF一直是我喜欢的一个ORM框架,随着版本升级EF也发展到EF6.x,Entity Framework Core是一个支持跨平台的全新版本, ...
- Entity Framework Core 2.0 中使用LIKE 操作符
Entity Framework Core 2.0 中使用LIKE 操作符 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译 ...
- 【EF】Entity Framework Core 2.0 特性介绍和使用指南
阅读目录 前言 获取和使用 新特性 项目升级和核心API变化 下一步计划 遗憾的地方 回到目录 前言 这是.Net Core 2.0生态生态介绍的最后一篇,EF一直是我喜欢的一个ORM框架,随着版本升 ...
- ASP.Net Core项目在Mac上使用Entity Framework Core 2.0进行迁移可能会遇到的一个问题.
在ASP.Net Core 2.0的项目里, 我使用Entity Framework Core 2.0 作为ORM. 有人习惯把数据库的连接字符串写在appSettings.json里面, 有的习惯写 ...
- ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0
ASP.NET 5.0 将改名为 ASP.NET Core 1.0 ASP.NET MVC 6 将改名为 ASP.NET MVC Core 1.0 Entity Framework 7.0 将 ...
- [转帖]2016年时的新闻:ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0
ASP.NET Core 1.0.ASP.NET MVC Core 1.0和Entity Framework Core 1.0 http://www.cnblogs.com/webapi/p/5673 ...
- Entity Framework Core 2.0 使用入门
一.前言 Entity Framework(后面简称EF)作为微软家的ORM,自然而然从.NET Framework延续到了.NET Core.以前我也嫌弃EF太重而不去使用它,但是EF Core(E ...
- Entity Framework Core 2.0 入门简介
不多说废话了, 直接切入正题. EF Core支持情况 EF Core的数据库Providers: 此外还即将支持CosmosDB和 Oracle. EFCore 2.0新的东西: 查询: EF.Fu ...
随机推荐
- linux下修改rm命令防止误删除
前言:相信很多朋友都遇到过在linux下用rm命令误删除文件的时候,此刻的心中仿佛有无数的羊驼在奔腾.那么怎么防止这种情况发生呢?当然是有方法的,我们可以写一个shell脚本,改变一下rm命令的作用. ...
- POJ-2299 Ultra-QuickSort (树状数组,离散化,C++)
Problem Description In this problem, you have to analyze a particular sorting algorithm. The algorit ...
- Java报文或者同步的数据有个别乱码情况的处理.
从其它系统获取到的用户数据,1万多条数据有其中有2条数据是乱码形式,这种形式表现为最后一个字符和本身的分隔符组成了一个乱码 错误数据 : 220296|+|黄燕 鄚+|7|+|7|+|02220 ...
- spring的一些问题
1.什么是spring? spring是一个轻量级的一站式框架,它的核心有两个部分,1.aop面向切面编程 2.ioc控制反转. 2.什么是aop aop就是面向切面编程,使用aop可以使业务逻辑各个 ...
- 浅谈大数据和hadoop家族
按照时间的早晚从大数据出现之前的时代讲到现在.暂时按一个城市来比喻吧,反正Landscape的意思也大概是”风景“的意思. 早在大数据概念出现以前就存在了各种各样的关于数学.统计学.算法.编程语言的研 ...
- BZOJ2748_音量调节_KEY
[HAOI2012]音量调节 Time Limit: 3 Sec Memory Limit: 128 MB Description 一个吉他手准备参加一场演出.他不喜欢在演出时始终使用同一个音量,所以 ...
- touch.js——常见应用操作
touch.js--常见应用操作 基本事件: touchstart //手指刚接触屏幕时触发 touchmove //手指在屏幕上移动时触发 touchend //手指从屏幕上移开时 ...
- 3.bootstrap-组件
1.图标 <button type="button" class="btn btn-default"> <span class="g ...
- java集合系列——Map之TreeMap介绍(九)
一.TreeMap的简介 TreeMap是一个有序的key-value集合,基于红黑树(Red-Black tree)的 NavigableMap实现.该映射根据其键的自然顺序进行排序,或者根据创建映 ...
- 如何写一个jquery插件
本文总结整理一下如何写一个jquery插件?虽然现今各种mvvm框架异常火爆,但是jquery这个陪伴我们成长,给我们带来很多帮助的优秀的库不应该被我们抛弃,写此文章,作为对以往欠下的笔记的补充, ...
