如何在代码优先中设置身份种子值?

Tim*_*mes 5 c# entity-framework entity-framework-core

我们将 Code First 与 EF-core 一起使用,我想添加一个列,该列的身份种子从 1 以外的另一个值开始。

目前,我们可以EntityTypeBuilder使用以下方法通过迁移期间将其设置为自动递增:

entityBuilder.Property(e => e.PropertyName).ValueGeneratedOnAdd();
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何更改身份种子。它是否仍然需要像其他版本的 EF 一样进行更新?例如,编写一些自定义 sql 并在迁移期间运行它?

如何首先在实体框架代码中为多个表播种身份种子值

如何首先使用 Entity Framework 4 代码和 SQL Compact 4 在 ID 列上设置标识种子?

在 EF-core 中似乎没有代码SqlServerMigrationSqlGenerator > override Generate(AlterTableOperation alterTableOperation)

小智 8

2020 年更新

在 EF Core 3.0 之后,您现在有一个UseIdentityColumn扩展方法,可用于设置标识列的种子和增量值。

builder.Property(prop => prop.Id)
            .UseIdentityColumn(10000000, 1);
Run Code Online (Sandbox Code Playgroud)

根据官方文件:

UseIdentityColumn 配置键属性以使用 SQL Server IDENTITY 功能为目标 SQL Server 生成新实体的值。此方法将属性设置为 OnAdd。

关联


Sin*_*tfi 7

在 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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)