1. 程式人生 > >Entity Framework Core 2.0 使用程式碼進行自動遷移

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();
}

執行效果: