EF核心迁移 - 添加带有唯一索引的新列现有数据库

发布于 2025-01-30 11:09:19 字数 830 浏览 4 评论 0原文

我有一个带有数据的现有表,我想在其中添加一个新列。

我必须为列设置默认值,但是当我执行迁移时,它会抱怨它。如果我不设置默认值,它也会抱怨,因为所有值都是null,这也不是唯一的。

错误:

创建唯一索引语句终止了,因为重复键 找到了对象名称“ powder.powderbox”和索引名称 'ix_powderbox_code'。重复的密钥值是(...)。

配置

builder.Property(x => x.Code)
       .IsRequired()
       .HasMaxLength(14);

builder
   HasIndex(x => x.Code)
   IsUnique();

迁移:

migrationBuilder.AddColumn<string>(
   name: "Code",
   schema: "powder",
   table: "PowderBox",
   type: "nvarchar(14)",
   maxLength: 14,
   nullable: false,
   defaultValue: "...";

migrationBuilder.CreateIndex(
   name: "IX_PowderBox_Code",
   schema: "powder",
   table: "PowderBox",
   column: "Code",
   unique: true);

如何在具有唯一索引的现有表中添加新列?

I have an existing table with data and I want to add a new column to it.

I have to set a default value for the column, but its complaining about it when I execute my migration. If I do not set a default value, it will also complain because all the values are null, which is also not unique.

Error:

The CREATE UNIQUE INDEX statement terminated because a duplicate key
was found for the object name 'powder.PowderBox' and the index name
'IX_PowderBox_Code'. The duplicate key value is (...).

Configuration

builder.Property(x => x.Code)
       .IsRequired()
       .HasMaxLength(14);

builder
   HasIndex(x => x.Code)
   IsUnique();

Migrations:

migrationBuilder.AddColumn<string>(
   name: "Code",
   schema: "powder",
   table: "PowderBox",
   type: "nvarchar(14)",
   maxLength: 14,
   nullable: false,
   defaultValue: "...";

migrationBuilder.CreateIndex(
   name: "IX_PowderBox_Code",
   schema: "powder",
   table: "PowderBox",
   column: "Code",
   unique: true);

How can I add a new column to an existing table with a unique index?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文