我遇到了一个问题,我试图在已经应用了迁移的数据库上回滚迁移。
这是我得到的错误:
Failed executing DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
ALTER TABLE [EventStaffRequest] ADD CONSTRAINT [PK_EventStaffRequest] PRIMARY KEY ([Id]);
System.Data.SqlClient.SqlException (0x80131904): Column 'Id' in table 'EventStaffRequest' is of a type that is invalid for use as a key column in an index.
Could not create constraint or index. See previous errors.
ClientConnectionId:29574816-2b1a-4490-a216-a54cd7a2d33b
Error Number:1919,State:1,Class:16
Column 'Id' in table 'EventStaffRequest' is of a type that is invalid for use as a key column in an index.
Could not create constraint or index. See previous errors.
这是我试图回滚的迁移:
public partial class AddedCompositeKeyToEventStaffRequest : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest");
migrationBuilder.DropIndex(
name: "IX_EventStaffRequest_EventId",
table: "EventStaffRequest");
migrationBuilder.DropColumn(
name: "Id",
table: "EventStaffRequest");
migrationBuilder.AddPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest",
columns: new[] { "EventId", "QualityTypeId" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest");
migrationBuilder.AddColumn<string>(
name: "Id",
table: "EventStaffRequest",
nullable: false,
defaultValue: "");
migrationBuilder.AddPrimaryKey(
name: "PK_EventStaffRequest",
table: "EventStaffRequest",
column: "Id");
migrationBuilder.CreateIndex(
name: "IX_EventStaffRequest_EventId",
table: "EventStaffRequest",
column: "EventId");
}
}
如果相关,这是我的型号代码:
public class EventStaffRequest
{
[Required]
public string EventId { get; set; }
public virtual Event Event { get; set; }
[Required]
public string QualityTypeId { get; set; }
public virtual QualityType QualityType { get; set; }
[Required]
public int AmountRequired { get; set; }
[Required]
public int MinimumRating { get; set; }
}
创建此迁移是因为我决定将主键更改为复合键。我在我的DbContext中应用了这样的复合主键(这是您在迁移中看到的Up()
我猜):
builder.Entity<EventStaffRequest>()
.HasKey(esr => new { esr.EventId, esr.QualityTypeId });
为什么我的回滚没有成功?我不明白为什么string
不适合密钥索引(我使用GUID作为密钥)。
答案 0 :(得分:3)
迁移系统似乎存在问题。问题不在于string
(当然它可以用于PK),而是maxLength
。默认情况下,string
列的长度不受限制,但PK需要应用一些限制。
通常当你使用string
列作为PK时,即使你没有指定maxLength
,EF也会自动应用一些限制(从我看到的,至少对于SqlServer来说它是{{1} })。有趣的是,按照相反的顺序执行相同的操作会生成类似的迁移,450
和Up
内容交换,Down
完全相同的代码可以正常工作。但不是在AddColumn
方法中执行时,因此在该路径中必定存在差异(因此存在问题)。您可以考虑将其发布在EF Core问题跟踪器中,以便他们知道(并最终修复它)。
无论如何,解决方案是明确将Down
参数添加到maxLength
来电:
AddColumn