使用 Entity Framework Core 时,通过代码自动 Migration
一 介绍
在使用 Entity Framework Core (下面就叫 EF Core 吧)进行开发时,如果模型有变动,我们要在用 EF Core 提供的命令行工具进行手工迁移,然后再运行程序。但是为了效率,我想能不能在程序的入口处进行 Migration 呢?从个人经验来说应该是可以,因为 EF Tool 虽然提供了 CLI 但是它最终也是被程序解析这些命令。下面就开始分析,如何通过代码进行 Migration 。
二 分析
首先我们要先了解,在使用 EF Core 的 CLI 时,要执行两个步骤:
第一步:生成 Migration 文件;
第二步:更新变更项到数据库;
既然是先生成 Migration 文件再更新,那么在 EF Core 里面一定有对应的模块做这件事情。下面我们看一下 EF Core 项目的结构。从中我们确实找到关于 Migration 的模块。在 Migrations/Design 目录的类名称上我们可以看出来,它就是生成 Migration 文件的。这里先到这儿。

找到了生成 Migration 文件的入口,我们再来找一下如何通过代码将这些变更更新到数据库中。
在使用 EF Core 的时候,我们都要通过继承 DbContext 来编写自己的 DbContext 子类。在 DbContext 类中我们找到了一个 Database 属性。如下图所示:

然后查看了 DatabaseFacde 这个类,并没有发现执行迁移相关的函数。通过代码搜索,我在 RelationalDatabaseFacadeExtensions 这个类中有一个 Migration() 扩展方法。通过注释的解析,我也确定了它就是执行 Migration 文件,并将变更更新到数据库。
这两个步骤对应的代码我们都找到了,下面我们就编写一段儿代码,完成自动将模型变更更新到数据库的功能。
public class AutoMigration
{
private readonly IServiceProvider _serviceProvider;
private InformationDbContext _context; public AutoMigration(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_context = serviceProvider.GetService<InformationDbContext>();
} public void Migrator()
{
var path = Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\Migrations\\");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
else
{
Directory.GetFiles(path).ToList().ForEach(File.Delete);
} using (_context)
{
var services = ((IInfrastructure<IServiceProvider>) _context).Instance;
var codeHelper = new CSharpHelper();
var scaffolder = ActivatorUtilities.CreateInstance<MigrationsScaffolder>(services,
new CSharpMigrationsGenerator(codeHelper, new CSharpMigrationOperationGenerator(codeHelper),
new CSharpSnapshotGenerator(codeHelper))); var projectDir = Path.Combine(path, "..\\");
var migrationAssembly = new MigrationsAssembly(new CurrentDbContext(_context), _context.Options, new MigrationsIdGenerator());
scaffolder.GetType().GetField("_migrationsAssembly", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(scaffolder, migrationAssembly); var readonlyDic = new ReadOnlyDictionary<string,TypeInfo>(new Dictionary<string, TypeInfo>());
migrationAssembly.GetType().GetField("_migrations", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(migrationAssembly, new LazyRef<IReadOnlyDictionary<string, TypeInfo>>(readonlyDic));
var migration = scaffolder.ScaffoldMigration("Information.Migrations", "Information"); scaffolder.Save(projectDir, migration, path); //另外一种保存方式
//File.WriteAllText($"Migrations\\{migration.MigrationId}{migration.FileExtension}", migration.MigrationCode);
//File.WriteAllText("Migrations\\" +
// migration.MigrationId + ".Designer" + migration.FileExtension,
// migration.MetadataCode);
//File.WriteAllText("Migrations\\" + migration.SnapshotName + migration.FileExtension,
// migration.SnapshotCode);
} using(_context = (InformationDbContext)_serviceProvider.GetService<IDbContext>())
{
_context.Database.Migrate();
}
}
}
另外一个注意点:我们需要指定一下迁移文件所在项目。
services.AddDbContext<InformationDbContext>(opt =>
{
var connectionString = configuration["ConnectionStrings:DefaultConnection"];
opt.UseSqlServer(connectionString, optionBuilder =>
{
optionBuilder.MigrationsAssembly("Information");
});
});
三 总结
通过上面的分析可以知道,其实我们就是把 CLI 的两个命令通过代码实现了一下。在 Startup 文件中进行调用即可。为什么想这么干?因为在实际开发的时候,来回切换窗口心里觉得不爽了呗。:)
使用 Entity Framework Core 时,通过代码自动 Migration的更多相关文章
- 对Entity Framework Core的一次误会:实体状态不跟踪
在 Entity Framework 中,当通过 EF 使用 LINQ 查询获取到一个实体(实际得到的是 EF 动态生成的实体类的代理类的实例)时,这个实体的状态默认是被跟踪的.所以,当你修改实体的某 ...
- Entity Framework Core 2.0 使用代码进行自动迁移
一.前言 我们在使用EF进行开发的时候,肯定会遇到将迁移更新到生产数据库这个问题,前面写了一篇文章介绍了Entity Framework Core 2.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 实现MySQL 的TimeStamp/RowVersion 并发控制
将通用的序列号生成器库 从SQL Server迁移到Mysql 遇到的一个问题,就是TimeStamp/RowVersion并发控制类型在非Microsoft SQL Server数据库中的实现.SQ ...
- 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)
在开发涉及到数据库的程序时,常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况,这时就需要进行数据库迁移. 实现数据库迁移有很多种办法,从手动管理各个版本的ddl脚本,到实现自己的mig ...
- Entity Framework Core 1.1 Preview 1 简介
实体框架核心(EF Core)是Entity Framework的一个轻量级,可扩展和跨平台版本. 10月25日,Entity Framework Core 1.1 Preview 1发布了. 升级到 ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 更新关系数据
Updating related data¶ 7 of 7 people found this helpful The Contoso University sample web applicatio ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 读取关系数据
Reading related data¶ 9 of 9 people found this helpful The Contoso University sample web application ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 创建复杂数据模型
Creating a complex data model 创建复杂数据模型 8 of 9 people found this helpful The Contoso University sampl ...
随机推荐
- Index was outside the bounds of the array. (Microsoft.SqlServer.Smo)
本地ssms是 安装Sqlserver 2008 r2 自带的 远端的server是sqlserver2014 可以连接,可以执行查询语句.但是,不能使用ssms生成对象的脚本.推测ssms 2008 ...
- 安装中文版cacti监控华为交换机流量并实现95计费
摘要:一. 装置yum源: 以网易yum源为例 1. 下载repo文件 下载地点:http://mirrors.163.com/.help/CentOS6-Base-163.repo 2.备份并调换体 ...
- [AIR] AIR 应用程序的调用和终止
本节讨论几种对已安装的 Adobe® AIR® 应用程序进行调用的方法,以及关闭运行中的应用程序的选项和注意事项. 注: NativeApplication.InvokeEvent 和 Browser ...
- 【OpenCV练习】简单显示图片的代码
今天依照网上的教程尝试了一下最基本的图片显示. 首先想说一下编译时出现的问题,开始时在编译时会出现无法识别cvReleaseImage的情况,是因为没有在配置中包含相应的core的库文件. 加进去就解 ...
- CentOS7:安装Zabbix
参考:CentOS 7 yum安装Zabbix 1. 安装Zabbix Server EPEL源里面有Zabbix的安装包,所以需要先安装EPEL. Zabbix源也可以从这里获得:http://re ...
- 通过js获取cookie的实例及简单分析
今天碰到一个在firefox下swfupload 上传时session不一致问题 在一个项目遇到多文件上传时,firefox下,服务器端的session获取不一致问题. 解决办法: 解决办法:将ses ...
- SplendidCRM中给来自EditView中的listbox控件设置选中值或数据源
DropDownList list = this.findContol("aas") as DropDownList;list.DataSource = new DataTable ...
- 慕课网-Java入门第一季-7-4 编程练习
来源:http://www.imooc.com/code/1634 小伙伴们,请根据所学知识,参考注释,在代码编辑器中将代码补充完整.编写一个 Java 程序,实现输出学生年龄的最大值 要求: 1. ...
- Node.js 自学之旅
学习基础,JQuery 原生JS有一定基础,有自己一定技术认知(ps:原型链依然迷糊中.闭包6不起来!哎!) 当然最好有语言基础,C#,java,PHP等等.. 最初学习这个东西的原因很简单,在园子里 ...
- 《疯狂Java讲义》(一) ---- 关于学习Java的反思
"听到Spring很火,就立马买来一本Spring的书来读,最后结果往往是失败,因为这种学习没有积累,没有根基,学习过程中困难重重,每天都被一些相同.类似的问题所困扰,起初热情十足,经常上论 ...