EF Code First - how to set identity seed?

爷,独闯天下 提交于 2019-11-26 20:52:44
Ladislav Mrnka

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...?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!