如何在DbMigrationConfiguration派生类中按顺序运行AddOrUpdate [英] How to make the AddOrUpdate run in order in DbMigrationConfiguration Derived class

查看:586
本文介绍了如何在DbMigrationConfiguration派生类中按顺序运行AddOrUpdate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我启用了迁移,我对种子代码进行编码,如下所示:

I enabled the migration, and I code the seed codes like follow:

protected override void Seed(DbContext c)
{
 c.DbSet<Table1>.AddOrUpdate(..);
 c.DbSet<Table2>.AddOrUpdate(..);
 c.DbSet<Table3>.AddOrUpdate(..);
}

我需要按顺序运行table1,因为table2引用了table1, table3引用table1和table2。

I need the table1 run in order, because the table2 references table1, and the table3 references table1 and table2.

但是EF6已经优化了代码生成的T-SQL批次,他们查询table1的table3引用,没有什么因为table1 hasn没有初始化,EF6抛出异常。

but the EF6 has optimized the code generated T-SQL batchs, they query the table1 for table3's references, and there is nothing due to table1 hasn't initialized yet, and EF6 throw a exception.

推荐答案

如果您在应用程序上下文类中定义了DbSets,例如对于Table1,将是:

If you have defined the DbSets in the application context class, for example for Table1 it would be:

public DbSet<Table1> Table1 { get; set; }

为什么不尝试写这样的语句: c.Table1.AddOrUpdate(...)?并且如果不起作用,则可以在每个语句之后尝试添加 c.SaveChanges(),以便对Table1所做的任何更改都将保存到DB中,然后再继续执行下一个声明当然这样会比较慢,但是如果种子方法不经常运行,那么这不会是一个问题?

why don't you try the to write the statement like this: c.Table1.AddOrUpdate(...)? and if that doesn't work you can try and add c.SaveChanges() after each statement so that any changes you make to Table1 is saved to the DB before proceeding to the next statement. Of course it will be slower but if the seed method is not run often maybe that won't be a problem?

这篇关于如何在DbMigrationConfiguration派生类中按顺序运行AddOrUpdate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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