【问题标题】:How to set Identity Seed value in code-first?如何在代码优先中设置身份种子值?
【发布时间】:2021-08-02 18:17:20
【问题描述】:
【问题讨论】:
标签:
c#
entity-framework
entity-framework-core
【解决方案1】:
2020 年更新。
在 EF Core 3.0 之后,您现在有了一个 UseIdentityColumn 扩展方法,可用于设置标识列的种子值和增量值。
builder.Property(prop => prop.Id)
.UseIdentityColumn(10000000, 1);
根据官方文档:
UseIdentityColumn 配置键属性以在面向 SQL Server 时使用 SQL Server IDENTITY 功能为新实体生成值。此方法将属性设置为 OnAdd。
Link
【解决方案2】:
在 Entity Framework Core 中使用Sql 命令在Up 方法中:
重要部分:migrationBuilder.Sql("DBCC CHECKIDENT ('Payment', RESEED, 1000000)");
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
namespace PaymentService.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Payment",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
},
constraints: table =>
{
table.PrimaryKey("PK_Payment", x => x.Id);
});
// Below code is for seeding the identity
migrationBuilder.Sql("DBCC CHECKIDENT ('Payment', RESEED, 1000000)");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "Payment");
}
}
}
【解决方案3】:
是的,你必须编写所需的SQL语句来设置种子,然后在迁移中使用Sql方法。
【解决方案4】:
如果您使用的是 MySQL 而不是 SQL Server,请添加以下内容来代替第一个答案中的 "migrationBuilder.Sql("DBCC CHECKIDENT ('Payment', RESEED, 1000000)");":
migrationBuilder.Sql("use db_name; ALTER TABLE Clients AUTO_INCREMENT = start_value;");