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?
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.
Based on Ladislav Mrnka's answer, you could add this in your migration file Up
method:
Sql("DBCC CHECKIDENT ('TableName', RESEED, NewSeedValue)");
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
You can defninitely achieve the same output as identity seed being 1000 by executing the "DBCC CHECKIDENT ('TableName', RESEED, NewSeedValue)" script from the Up method of migration script.
However, the table definition in SQL Server still shows "IDENTITY(1,1)" even though the first record entered in the table gets an id 1000. This means that the the identity seed of the table has actually not been set to 1000. It's just that the initial 999 values are consumed or skipped while creating the first record, of course because you are firing the RESEED command to the DB i.e. you are changing the SEED that has already been set.
To conclude, it looks like, in EF core v2.1, Microsoft has not provided the provision of customizing the identity seed value while creating the table. Let us hope that the future versions of EF Core, probably 2.2 or 3.0 will have this feature. Thoughts...?
来源:https://stackoverflow.com/questions/5974554/ef-code-first-how-to-set-identity-seed