Entity Framework auto increment with starting value

auto-increment entity-framework entity-framework-6

Question

I have the following entity:

[Table("ESS_POS_SE_VERSION")]
public class Version
{
    [Key, Column("DETAIL_ID"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column("DETAIL_TITILE")]
    public string DetailKey { get; set; }

    [Column("DETAIL")]
    public string Detail { get; set; }
}

I need to set the starting value of the SO Id column to 1000 even though it is an auto-increment column. How do I go about doing it?

1
4
5/31/2014 8:09:33 AM

Accepted Answer

Think about developing a unique database initializer. Every time your database is built or recreated, it will be called.

For instance:

public class MyInitializer : DropCreateDatabaseIfModelChanges<TContext> where TContext : DbContext
{
    protected override void Seed(TContext context)
    {
        context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('MyTable', RESEED, 1000);");
    }
}

then record it:

protected void Application_Start()
{
    Database.SetInitializer<MyContext>(new MyInitializer());
}
9
5/31/2014 8:21:56 AM

Popular Answer

Neither property nor attribute may be used to set anything. But you can execute the following command on this event:

Most likely, you can change using Alter: ALTER TABLE [MyTable] [IdentityColumn] ALTER COLUMN IDENTITY (1000,1).

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    { context.Database.ExecuteSqlCommand(ALTER TABLE [MyTable] ALTER COLUMN [IdentityColumn] IDENTITY (1000,1)) }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow