Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - How to make the AddOrUpdate run in order in DbMigrationConfiguration Derived class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...