如何种子数表中的实体框架代码标识种子值第一 [英] How to seed identity seed value in entity framework code first for several tables

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

问题描述

我已经看到并的this 。我只想第一种子ID列起始值为我的代码(EF6.1)表。现在我能做到这一点。

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?

感谢

推荐答案

您可以尝试使用此>

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

您可以使用多种不同的选择,而不是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天全站免登陆