简体   繁体   English

如何首先在实体框架代码中为几个表播种标识种子值

[英]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. 我只是希望为我的代码优先(EF6.1)表的ID列的起始值设定种子。 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. 您可以使用多种不同的选项来代替AlterTableOperation,添加列,重命名列等,以触发此操作在每个表上运行。 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. 另一种方法是在SQL Server中编写脚本-而不是每天或每周发生一次。 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. 但是,如果您需要定期在所有表上(而不是在SQL Server中)进行某些操作,那么我认为上述方法是可行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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