如何在几个表中首先为实体框架代码种子识别种子值 [英] How to seed identity seed value in entity framework code first for several tables

查看:78
本文介绍了如何在几个表中首先为实体框架代码种子识别种子值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到这个 this 。我只想为我的代码(EF6.1)表格的ID列的起始值进行种子化。现在我可以这样做

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?

谢谢

推荐答案

你可以尝试使用这个:

    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));
            }
        }
    }

您可以使用大量不同的选项而不是AlterTableOperation,添加一个列,重命名列等来触发它在每个表上运行。不幸的是,你必须做一些更新每个表的内容,以便在每个表上注入自己的操作。

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.

另一种方法是在SQL Server中脚本化 - 它不像每天或每周发生一次。通过桌面迭代,重新设置每个种子。但是,如果您需要定期在所有表上发生任何事情,而不是在SQL Server中发生事情,那么我认为上述是要走的路。

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.

这篇关于如何在几个表中首先为实体框架代码种子识别种子值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆