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

南楼画角 提交于 2019-12-19 10:54:56

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/28920768/how-to-seed-identity-seed-value-in-entity-framework-code-first-for-several-table

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