EF Core - 删除列解决方法(sqlite)

joh*_*son 2 sql sqlite entity-framework-core

记载,EF 核心迁移脚本不支持删除列。所以我正在尝试手动完成。

我的模型类是:

class Master
{
    public int Id { get; set; }
    public string ToBeDeleted { get; set; }
}

class Detail
{
    public int Id { get; set; }

    public Master Master { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的背景:

class Context : DbContext
{
    public DbSet<Master> Masters { get; set; }
    public DbSet<Detail> Details { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=local.db");
        base.OnConfiguring(optionsBuilder);
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个迁移脚本,然后运行以下程序来创建 db 文件并添加几行:

class Program
{
    static void Main(string[] args)
    {
        using (var context = new Context())
        {
            context.Database.Migrate();
            if(!context.Masters.Any())
            {
                var master = new Master {ToBeDeleted = "Some string"};
                context.Add(master);
                context.Add(new Detail {Master = master});
                context.SaveChanges();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我删除ToBeDeletedMaster类的属性并生成了第二个迁移脚本,该脚本生成了非常简单的代码,但该代码不起作用,因为它只会在未来得到支持:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.DropColumn(
        name: "ToBeDeleted",
        table: "Masters");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
   migrationBuilder.AddColumn<string>(
        name: "ToBeDeleted",
        table: "Masters",
        nullable: true);
}
Run Code Online (Sandbox Code Playgroud)

所以是时候写我自己的东西了,这就是我尝试过的:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql("PRAGMA foreign_keys=OFF");
    migrationBuilder.CreateTable(
        name: "NEW_Masters",
        columns: table => new
        {
             Id = table.Column<int>(nullable: false)
                .Annotation("Sqlite:Autoincrement", true),
        },
         constraints: table =>
         {
             table.PrimaryKey("PK_Masters", x => x.Id);
         });
    migrationBuilder.Sql("INSERT INTO NEW_Masters SELECT Id FROM Masters;");
    migrationBuilder.DropTable("Masters");
    migrationBuilder.RenameTable("NEW_Masters", newName: "Masters");
    migrationBuilder.Sql("PRAGMA foreign_keys=OFF");
}
Run Code Online (Sandbox Code Playgroud)

但是这会导致context.Database.Migrate()抛出异常:

Microsoft.EntityFrameworkCore.Relational.dll 中发生类型为“Microsoft.Data.Sqlite.SqliteException”的未处理异常

附加信息:SQLite 错误 19:“FOREIGN KEY 约束失败”。

最后,问题:如何在迁移脚本中手动删除列?

更新

按照我在讨论中得到的建议,我曾经Script-Migration从迁移脚本生成 sql 并得到这个:

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

CREATE TABLE "Masters" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_Masters" PRIMARY KEY AUTOINCREMENT,
    "ToBeDeleted" TEXT
);

CREATE TABLE "Details" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_Details" PRIMARY KEY AUTOINCREMENT,
    "MasterId" INTEGER,
    CONSTRAINT "FK_Details_Masters_MasterId" FOREIGN KEY ("MasterId") REFERENCES "Masters" ("Id") ON DELETE RESTRICT
);

CREATE INDEX "IX_Details_MasterId" ON "Details" ("MasterId");

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20170127204056_Migration1', '1.1.0-rtm-22752');

INSERT INTO Masters (ToBeDeleted) VALUES ("ASDF"); --I've added this line manually for test only

INSERT INTO Details (MasterId) VALUES (1); --I've added this line manually for test only

PRAGMA foreign_keys="0";

CREATE TABLE "NEW_Masters" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_Masters" PRIMARY KEY AUTOINCREMENT
);

INSERT INTO NEW_Masters SELECT Id FROM Masters;;

DROP TABLE "Masters";

ALTER TABLE "NEW_Masters" RENAME TO "Masters";

PRAGMA foreign_keys="1";

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20170127204851_Migration2', '1.1.0-rtm-22752');
Run Code Online (Sandbox Code Playgroud)

并且脚本运行良好。例外是 EF 在某处执行的一些外键检查。

joh*_*son 5

EF核心开发人员指出,PRAGMA foreign_keys=0没有在SQLite的事务中的工作,并建议使用该migrationBuilder.Sql方法来禁止使用的交易。

所以我想出了:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "NEW_Masters",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("Sqlite:Autoincrement", true),
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Masters", x => x.Id);
            });
        migrationBuilder.Sql("INSERT INTO NEW_Masters SELECT Id FROM Masters;");
        migrationBuilder.Sql("PRAGMA foreign_keys=\"0\"", true);
        migrationBuilder.Sql("DROP TABLE Masters", true);
        migrationBuilder.Sql("ALTER TABLE NEW_Masters RENAME TO Masters", true);
        migrationBuilder.Sql("PRAGMA foreign_keys=\"1\"", true);
    }
Run Code Online (Sandbox Code Playgroud)

它可以解决问题。