Entity Framework 7 Identity Seed

眉间皱痕 提交于 2019-12-01 07:44:22

问题


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

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

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

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?

How to seed identity seed value in entity framework code first for several tables

How do I set Identity seed on an ID column using Entity Framework 4 code first with SQL Compact 4?

In EF7 there does not seem to be code for SqlServerMigrationSqlGenerator > override Generate(AltherTableOperation alterTableOperation)?


回答1:


In Entity Framework Core Use Sql Command in Up method:

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



回答2:


Yes, you must write the required SQL statement to set the seed, and then use the Sql method in the migration.



来源:https://stackoverflow.com/questions/34927619/entity-framework-7-identity-seed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!