Entity Framework 7 Identity Seed

c# entity-framework entity-framework-core


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)?

5/23/2017 11:52:26 AM

Accepted Answer

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)
            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/3/2018 8:46:45 AM

Popular Answer

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

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow