简体   繁体   中英

How to seed identity seed value in entity framework code first for several tables

I have seen this and this . I simply wish to seed the start value for ID columns for my code first ( EF6.1) tables. Now I can do this

public class CustomInitializer : CreateDatabaseIfNotExists<FormsDbContext>
{
    protected override void Seed(FormsDbContext context)
    {
        context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('MyTable', RESEED, 1000)");
    }
}

But as I have lots and lots of tables, I find it odd ( and it feels almost wrong) that I would have to repeat the above line for ALL of those. I haven't been able to find any way to do this with fluent configuration . Is this the correct way to do the seed?

Thanks

You could try using this:

    internal class DefaultMigrationSqlGenerator : SqlServerMigrationSqlGenerator
    {
        protected override void Generate(AlterTableOperation alterTableOperation)
        {
            base.Generate(alterTableOperation);
            // If the tables you want to reseed have an Id primary key...
            if (alterTableOperation.Columns.Any(c => c.Name == "Id"))
            {
                string sqlSeedReset = string.Format("DBCC CHECKIDENT ({0}, RESEED, 1000) ", alterTableOperation.Name.Replace("dbo.", ""));

                base.Generate(new SqlOperation(sqlSeedReset));
            }
        }
    }

You can use a multitude of different options instead of AlterTableOperation, add a column, rename a column etc. to trigger this to run on every table. Unfortunately, you will have to do something that updates every table to be able to inject your own action on each of them.

The alternative is to script it in SQL Server - it's not like it would be a daily or weekly occurrence. Iterate through the tables, resetting the seed on each. But if you need something to happen on all tables regularly, and not in SQL Server, then I think the above is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM