EF PostgeSQL 迁移脚本:如果不存在,则为 CREATE 表

EF PostgeSQL migrations script: CREATE Table if it doesn't exist

提问人:Anna Melashkina 提问时间:11/16/2023 最后编辑:marc_sAnna Melashkina 更新时间:11/17/2023 访问量:37

问:

在我的项目中,我有这样的迁移:

public partial class InitialCreate : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Studios",
            columns: table => new
            {
                Id = table.Column<Guid>(nullable: false),
                Company = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Studios", x => x.Id);
            });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Studios");
    }
}

我正在使用 PostgeSQL ()。pgsql.EntityFrameworkCore.PostgreSQL

我使用 或 生成 SQL 文件,它生成此 SQL 文件:Script-Migrationdotnet ef migrations script

CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" 
(
    "MigrationId" character varying(150) NOT NULL,
    "ProductVersion" character varying(32) NOT NULL,
    CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);

START TRANSACTION;

CREATE TABLE "Studios" 
(
    "Id" uuid NOT NULL,
    "Company" text NULL,
    CONSTRAINT "PK_Studios" PRIMARY KEY ("Id")
);

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20210202135422_InitialCreate', '7.0.13');

COMMIT;

这个 SQL 我可以运行,但只能运行一次。因为对于第二次运行,它将失败

错误:关系“Studios”已存在

我的问题是,为什么它会生成这样的 SQL?为什么它不生成以及如何修复它?CREATE TABLE IF NOT EXISTS "Studios"

PostgreSQL 核心 实体框架迁移

评论

0赞 Svyatoslav Danyliv 11/17/2023
来自文档:幂等 SQL 脚本

答:

0赞 Anna Melashkina 11/17/2023 #1

@Svytoslav是对的。我错过了,如果我们不知道数据库的当前状态,就会产生迁移。--idempotent

https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying?tabs=dotnet-core-cli#idempotent-sql-scripts