Entity Framework auto increment with starting value

白昼怎懂夜的黑 提交于 2019-11-29 05:11:36

Consider creating a custom database initializer. It will be called each time your database is created or recreated.

For example:

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

Then register it:

protected void Application_Start()
{
    Database.SetInitializer<MyContext>(new MyInitializer());
}

There is no way to set through Property or Attribute. However, you can run the command on this event:

Probably you can set through Alter: ALTER TABLE [MyTable] ALTER COLUMN [IdentityColumn] IDENTITY (1000,1).

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    { context.Database.ExecuteSqlCommand(ALTER TABLE [MyTable] ALTER COLUMN [IdentityColumn] IDENTITY (1000,1)) }
context.Database.ExecuteSqlCommand("ALTER TABLE Version ALTER COLUMN DETAIL_ID IDENTITY (1000,1)");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!