Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
Achinth Gurkhi Avatar asked May 12 '11 07:05

Achinth Gurkhi


People also ask

What is identity seed?

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.

How do I get identity value in EF core?

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();

How do I make Entity Framework Code First?

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…


3 Answers

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.

like image 177
Ladislav Mrnka Avatar answered Oct 04 '22 08:10

Ladislav Mrnka


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

Sql("DBCC CHECKIDENT ('TableName', RESEED, NewSeedValue)");
like image 26
Ehsan88 Avatar answered Oct 04 '22 07:10

Ehsan88


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

like image 21
kareem khalil Avatar answered Oct 04 '22 08:10

kareem khalil