我在项目中使用MySQL数据库时遇到问题。通常,某些项目表在输入数据时需要具有一个自动递增字段。但是,在MySQL中,如果ID是唯一键,则只有Id以外的列才能自动递增。例如:
public class Client
{
[Key]
public Guid Id { get; set; }
[MaxLength(200)]
public string Name { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Code { get; set; }
public DateTime BirthDate { get; set; }
}
但是,在MySQL中,只有Id
以外的列才能唯一地自动递增。例如:
modelBuilder.Entity<Client>()
.HasIndex(c => c.Code)
.IsUnique();
到目前为止很好。 Code
正确且正在编译。但是,生成迁移时,结果是:
第1部分:
migrationBuilder.CreateTable(
name: "Client",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Code = table.Column<int>(nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(maxLength: 200, nullable: false),
BirthDate = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Client", x => x.Id);
}
);
第2部分:
migrationBuilder.CreateIndex(
name: "IX_Client_Code",
table: "Client",
column: "Code",
unique: true);
行政执法人员(database update
)遇见性犯罪事实[Incorrect table definition; there can be only one auto column and it must be defined as a key
。
此错误是由创建迁移的方式引起的。在上面的代码的第一部分中,已经明确指出“代码”为MySqlValueGenerationStrategy.IdentityColumn
,因此会发生错误。为了解决此问题,我必须创建两个迁移:第一个迁移仅将Code
字段添加到单个字段,第二个插入自动增量。但是,我不想用这种方式,因为每次我都必须创建至少两个迁移。
注意:在这种情况下,我可以放弃GUID
”,而只对表使用Code
(int
),但这是不可能的,因为我必须修改所有表的结构。另外,我发现的另一个可能的解决方案是将ID和Code用作主键,但是我不太可能那样使用它。
有两种解决方法。
如果只想手动修复迁移代码,则不要使用CreateIndex
,而只需将替代键添加到创建表操作的约束中:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Client",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(maxLength: 200, nullable: true),
Code = table.Column<long>(nullable: false)
.Annotation("MySql:ValueGenerationStrategy",
MySqlValueGenerationStrategy.IdentityColumn),
BirthDate = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Client", x => x.Id);
table.UniqueConstraint("AK_Client", x => x.Code); // <-- Add unique constraint
});
}
没有数据注释来定义备用键,但是您可以使用fluent API:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Client>(entity => entity.HasAlternateKey(e => e.Code));
}
这将创建与上面相同的工作迁移代码,并导致以下CREATE TABLE
语句:
CREATE TABLE `Client` (
`Id` char(36) NOT NULL,
`Name` varchar(200) CHARACTER SET utf8mb4 NULL,
`Code` bigint NOT NULL AUTO_INCREMENT,
`BirthDate` datetime(6) NOT NULL,
CONSTRAINT `PK_Client` PRIMARY KEY (`Id`),
CONSTRAINT `AK_Client` UNIQUE (`Code`)
);
使用HasIndex().IsUnique()
将不起作用,因为这将产生与您在问题中描述的问题相同的CreateIndex()
呼叫。