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

时间:2017-01-27 20:58:44

标签: sql sqlite entity-framework-core

is documented并且已知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; }
}

我的背景:

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

我创建了一个迁移脚本,然后运行以下程序来创建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();
            }
        }
    }
}

我删除了ToBeDeleted类的Master属性并生成了第二个迁移脚本,该脚本生成了非常简单的代码,该代码不起作用,因为它将来只会被支持:

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

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

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

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

  

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

中      

其他信息: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');

脚本运行正常。例外情况是由EF在某处执行的一些外键检查。

2 个答案:

答案 0 :(得分:1)

EF core developers指出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);
    }

它可以解决问题。

答案 1 :(得分:0)

对于lazier,我所做的是手动删除解决方案中的迁移,然后sqlite db添加了迁移。当那个讨厌的错误出现而无法删除时,请注释掉up方法的主体,如下所示:在生成的脚本中。然后更新数据库。当我向用户添加参考对象类型SocialMediaLinks时,它生成了一个fk,对我来说很好。这对所有人来说都不是一个合适的解决方案,因为它可能会导致数据丢失.ALSO删除导致fk依赖的类实体。

//generated migration:

 protected override void Up(MigrationBuilder migrationBuilder)
        {
             //comment out--
            //migrationBuilder.DropColumn(
            //    name: "SocialMediaLinks",
            //    table: "ProfileUserVM");

            //migrationBuilder.DropColumn(
            //    name: "SocialMediaLinks",
            //    table: "AspUsers");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "SocialMediaLinks",
                table: "ProfileUserVM",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "SocialMediaLinks",
                table: "AspUsers",
                nullable: true);
        }