我在项目中使用 MySQL 数据库时遇到问题。一般来说,一些项目表需要在输入数据时有一个自动递增的字段。但是,在 MySQL 中,除了 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);
Ao executar a atualização do banco de dados ( database update
) a seguinte mensagem é exibida: Incorrect table definition; there can be only one auto column and it must be defined as a key
.
此错误是由创建迁移的方式引起的。在上面的代码的第一部分中,已经明确指出“代码”是MySqlValueGenerationStrategy.IdentityColumn
,因此会发生错误。为了解决这个问题,我必须创建两个迁移:第一个只将Code
字段添加到 single,第二个插入自动增量。但是,我不想以这种方式使用它,因为每次我都必须创建至少两个迁移。
注意:在这种情况下,我可以放弃GUID
`` 而只对表使用Code
( int
),但这是不可能的,因为我必须修改所有表的结构。另外,我发现的另一个可能的解决方案是将 ID 和 Code 设为主键,但我不太可能以这种方式使用它。