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
Comments
-
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 almost 13 yearsCode First, Database Specific SQL Last ;)
-
Ladislav Mrnka almost 13 yearsCode 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 over 7 yearsThank you for the solution working with VS only instead of SQL Server that requires more deployment efforts.
-
Mike Devenney almost 7 yearsIMHO - 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 about 5 yearsAnd 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 about 5 yearsIf 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
.