一.前言
我们在使用EF进行开发的时候,肯定会遇到将迁移更新到生产数据库这个问题,前面写了一篇文章介绍了Entity Framework Core 2.0的入门使用,这里面介绍了使用命令生成迁移所需的SQL,然后更新到生产数据库的方法。这里还有另一种方法,就是利用EF Core自身所提供的方法来进行迁移。
二.API说明
这些方法都是DatabaseFacade的扩展方法,我们常使用的DbContext.Database就是DatabaseFacade类型。
GetMigrations
获取所有迁移
///
/// Gets all the migrations that are defined in the configured migrations assembly.
///
public static IEnumerable GetMigrations([NotNull] this DatabaseFacade databaseFacade)
GetPendingMigrations
获取待迁移列表
///
/// Gets all migrations that are defined in the assembly but haven't been applied to the target database.
///
public static IEnumerable GetPendingMigrations([NotNull] this DatabaseFacade databaseFacade)
GetAppliedMigrations
获取执行了迁移的列表
///
/// Gets all migrations that have been applied to the target database.
///
public static IEnumerable GetAppliedMigrations([NotNull] this DatabaseFacade databaseFacade)
Migrate
执行迁移
///
///
/// Applies any pending migrations for the context to the database. Will create the database
/// if it does not already exist.
///
///
/// 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.
///
///
/// The for the context.
public static void Migrate([NotNull] this DatabaseFacade databaseFacade)
三.实现自动迁移
我们可以利用上面的方法,让程序在启动的时候检查是否有待迁移,如果有那么执行迁移。这里以一个.NET Core 控制台应用程序作为示例:
1.定义一个检查迁移的方法
///
/// 检查迁移
///
///
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);
...
}
}
运行:
四.制作一个单独的迁移工具
上面的方法需要我们每次在应用程序启动的时候都去检查迁移,我们也可以单独制作一个控制台程序来进行迁移的更新,这样只要在更新迁移的时候放到服务器上执行一下就行 了。
代码如下:
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();
}
执行效果: