如何在代码优先中设置“身份种子”值? [英] How to set Identity Seed value in code-first?

查看:90
本文介绍了如何在代码优先中设置“身份种子”值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们将代码优先与EF核心一起使用,我想添加一列,该列的身份种子的起始值应为1以外的另一个值。

We are using Code First with EF-core and I would like to add a column which has an Identity Seed starting at another value other to 1.

当前,我们可以将其设置为在迁移期间使用 EntityTypeBuilder 自动递增,

Currently we can set it to auto increment via the EntityTypeBuilder during migrations using:

entityBuilder.Property(e => e.PropertyName).ValueGeneratedOnAdd();

但是我找不到如何更改身份种子的方法。是否仍需要像其他版本的EF一样进行更新?例如

However I cannot find out how to change the identity seed. Does it still need to be updated like it was with other versions of EF? e.g. writing some custom sql and running this during migration?

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

如何做我首先在SQL Compact 4上使用Entity Framework 4代码在ID列上设置了身份种子?

在EF-core中似乎没有<$ c $的代码c> SqlServerMigrationSqlGenerator>重写Generate(AlterTableOperation alterTableOperation)?

In EF-core there does not seem to be code for SqlServerMigrationSqlGenerator > override Generate(AlterTableOperation alterTableOperation)?

推荐答案

在实体框架核心中使用 Up 方法中的Sql 命令:

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");
        }
    }
}

这篇关于如何在代码优先中设置“身份种子”值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆