EF Code First - how to set identity seed?
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?
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