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

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

问题描述

我们正在将 Code First 与 EF-core 一起使用,我想添加一个列,该列的身份种子从 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 一样进行更新?例如编写一些自定义 sql 并在迁移期间运行它?

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?

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

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

在 EF-core 中似乎没有 SqlServerMigrationSqlGenerator > 的代码.覆盖 Generate(AlterTableOperation alterTableOperation)?

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

推荐答案

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

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

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