EF Code First - how to set identity seed?

29,824

Solution 1

If you are using SQL Server you must create custom database initializer and manually execute DBCC CHECKIDENT ('TableName', RESEED, NewSeedValue). For creating and using custom initializer with custom SQL commands check this answer.

Solution 2

Based on Ladislav Mrnka's answer, you could add this in your migration file Up method:

Sql("DBCC CHECKIDENT ('TableName', RESEED, NewSeedValue)");

Solution 3

based on @ehsan88 you can make a Database Initialize class

 public class AccDatabaseInitializer : CreateDatabaseIfNotExists<YourContect>
    {
      protected override void Seed(YourContect context)
       {
          context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('TableName', RESEED, NewSeedValue)");
           context.SaveChanges();
       }
    }

thanks

Share:
29,824
Achinth Gurkhi
Author by

Achinth Gurkhi

Developer

Updated on September 04, 2020

Comments

  • Achinth Gurkhi
    Achinth Gurkhi over 3 years

    I have a entity class

    public class Employee
    {
        public long Id { get; set; }
        public string Name { get; set; }
    }
    

    I have set the Id field as the primary key with auto number generation

    modelBuilder.Entity<Employee>().HasKey(e => e.Id);
    modelBuilder.Entity<Employee>().Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    

    But I want the Identity to seed from 10000 instead of from 1 which is the default. How can I specify this in EF?

  • Baldy
    Baldy almost 13 years
    Code First, Database Specific SQL Last ;)
  • Ladislav Mrnka
    Ladislav Mrnka almost 13 years
    Code first is based on the fact that you have absolutely no requirements on database. If you have requirements you must introduce database specific SQL.
  • Thomas.Benz
    Thomas.Benz over 7 years
    Thank you for the solution working with VS only instead of SQL Server that requires more deployment efforts.
  • Mike Devenney
    Mike Devenney almost 7 years
    IMHO - This should be the accepted answer. It's the more 'Code First' way to do it. Put all the database construction logic into the migrations so there's nothing to forget when you rebuild the db days/weeks/months later.
  • binki
    binki about 5 years
    And it is easier as a migration because that will only ever get run once. If you accidentally seed the column multiple times (e.g., by putting it in a data seeder/initializer instead of a migration), you’ll get an ID collision on your next INSERT.
  • binki
    binki about 5 years
    If you put this in a seeder, that seeder will run on each initialization. Then you’ll reset the value each time unless you manually calculate it. This leads to a constraint error on your next INSERT.