且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-07 13:09:32

在 Entity Framework Core 中使用 Sql 命令在 Up 方法中:

In Entity Framework Core Use Sql Command in Up method:

重要部分: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");
        }
    }
}