在我的项目中,我有这样的迁移:
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");
}
}
字符串
我使用的是PostgreSQL(pgsql.EntityFrameworkCore.PostgreSQL
)。
我使用Script-Migration
或dotnet ef migrations script
生成SQL文件,这会生成以下SQL文件:
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"
以及如何修复它?
1条答案
按热度按时间kknvjkwl1#
@Svytoslav是对的。我错过了,有一个标志
--idempotent
,如果我们不知道数据库的当前状态,它会生成迁移。https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying?tabs=dotnet-core-cli#idempotent-sql-scripts