问题
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