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?
IDENTITY[(seed,increment)] In this syntax: The seed is the value of the first row loaded into the table. The increment is the incremental value added to the identity value of the previous row.
EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();
Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With