EF核心迁移 - 添加带有唯一索引的新列现有数据库
我有一个带有数据的现有表,我想在其中添加一个新列。
我必须为列设置默认值,但是当我执行迁移时,它会抱怨它。如果我不设置默认值,它也会抱怨,因为所有值都是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论