How to make the AddOrUpdate run in order in DbMigrationConfiguration Derived class

こ雲淡風輕ζ 提交于 2019-12-13 10:27:52

问题


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

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

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.


回答1:


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

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

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?



来源:https://stackoverflow.com/questions/39589522/how-to-make-the-addorupdate-run-in-order-in-dbmigrationconfiguration-derived-cla

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