实体框架核心-获取待定迁移的脚本

时间:2019-04-11 12:47:43

标签: entity-framework-core ef-migrations

有没有一种方法可以确定运行时使用的迁移脚本

context.Database.Migrate();

在EF6中,我可以使用

System.Data.Entity.Migrations.Infrastructure.MigratorScriptingDecorator 

和方法

migrator.ScriptUpdate(null, null)

生成脚本,以便在出现问题时转储它们以进行故障排除。 ef-core是否有类似的方法?

1 个答案:

答案 0 :(得分:0)

这是一种方法,用于转储Entity Framework Core SQL脚本以进行故障排除,或使用Roundhouse之类的工具将其添加到源代码控制中以在CI / CD管道中使用。

请参阅:EFCoreHelper.cs

public static Dictionary<string, string> GetAllMigrationsSQL(DbContext db)
{            
    var migrationsSQL = new Dictionary<string, string>();
    var migrations = db.Database.GetMigrations();
    var migrator = db.GetService<IMigrator>();
    string fromMigration = null;
    foreach(var toMigration in migrations)
    {
        var sql = migrator.GenerateScript(fromMigration, toMigration);
        migrationsSQL.Add(toMigration, sql);
        fromMigration = toMigration;
    }
    return migrationsSQL;
}

使用语句使代码正常工作:

using System; //for the Console output
using System.Collections.Generic; //for the Dictionary type
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

我有forked the EFGetStarted project来演示如何使用代码。 SQL将生成并记录到控制台。使用的示例生成以下SQL:

--20190917222642_InitialCreate
CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
    "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY,
    "ProductVersion" TEXT NOT NULL
);

CREATE TABLE "Blogs" (
    "BlogId" INTEGER NOT NULL CONSTRAINT "PK_Blogs" PRIMARY KEY AUTOINCREMENT,
    "Url" TEXT NULL
);

CREATE TABLE "Posts" (
    "PostId" INTEGER NOT NULL CONSTRAINT "PK_Posts" PRIMARY KEY AUTOINCREMENT,
    "Title" TEXT NULL,
    "Content" TEXT NULL,
    "BlogId" INTEGER NOT NULL,
    CONSTRAINT "FK_Posts_Blogs_BlogId" FOREIGN KEY ("BlogId") REFERENCES "Blogs ("BlogId") ON DELETE CASCADE
);

CREATE INDEX "IX_Posts_BlogId" ON "Posts" ("BlogId");

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20190917222642_InitialCreate', '3.1.8');

感谢JiříČinčuraGenerating Entity Framework Core Migrations script from code