gpt4 book ai didi

entity-framework-core - Entity Framework Core - 获取挂起迁移的脚本

转载 作者:行者123 更新时间:2023-12-05 07:24:00 28 4
gpt4 key购买 nike

有没有办法确定运行时使用的迁移脚本

context.Database.Migrate();

在 EF6 中,我可以使用

System.Data.Entity.Migrations.Infrastructure.MigratorScriptingDecorator 

和方法

migrator.ScriptUpdate(null, null)

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

最佳答案

这是一种转储 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 语句是:

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čura Generating Entity Framework Core Migrations script from code

关于entity-framework-core - Entity Framework Core - 获取挂起迁移的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55632886/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com