使用 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 ...
随机推荐
- Android学习笔记(十二)
Fragment是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用大屏幕的空间. 碎片的简单用法:新建一个FragmentTest项目,然后新建一个左侧碎片布局left_fragmen ...
- Windows服务器上使用bat定时执行php
windows上和linux上有一个类似的cmd和bat文件,bat文件类似于shell文件,执行这个bat文件,就相当于依次执行里面的命令(当然,还可以通过逻辑来实现编程),所以,我们可以利用bat ...
- Heka 的编译 和 Heka 插件的编译
相关英文文档在: https://hekad.readthedocs.io/en/latest/installing.html 所有系统都必须的如下: Prerequisites (all syste ...
- [转载]Java程序员使用的20几个大数据工具
最近我问了很多Java开发人员关于最近12个月内他们使用的是什么大数据工具. 这是一个系列,主题为: 语言web框架应用服务器SQL数据访问工具SQL数据库大数据构建工具云提供商今天我们就要说说大数据 ...
- archlinux 打印机驱动安装
#安装驱动# pacman -S cups ghostscript gsfonts gutenprint#启动服务# systemctl start/enable org.cups.cupsd.ser ...
- oracle 单列索引 多列索引的性能测试
清除oralce 缓存:alter system flush buffer_cache; 环境:oracle 10g . 400万条数据,频率5分钟一条 1.应用场景: 找出所有站点的最新一条数据. ...
- Have Fun with Numbers及循环链表(约瑟夫问题)
1. 循环链表(约瑟夫问题) https://github.com/BodhiXing/Data_Structure 2. Have Fun with Numbers https://pta.pate ...
- 500lines项目简介
"500行或更少" "What I cannot create, I do not understand." -- Richard Feynman <50 ...
- C# 访问MongoDB 通用方法类
using MongoDB.Driver; using System; namespace MongoDBDemo { public class MongoDb { public MongoDb(st ...
- Git--分布式版本控制系统
使用Git实现多人协作开发 1.简述 每创建一个大的web项目都会有团队协作完成, 然这个过程有可能就像毕业生写论文的过程, 这个过程会有很多...修改的版本, 我们的项目也是会经过无休止的改需求, ...