【问题标题】:Entityframework Core2.0 how to execute seed and migration in parallel [duplicate]Entity Framework Core 2.0如何并行执行种子和迁移[重复]
【发布时间】:2018-05-07 12:58:23
【问题描述】:

我正在使用迁移,也想使用种子数据。当前出现错误。实现这一目标的最佳方法是什么?

我之前在 stackoverflow 中的查询: previous post

谢谢

【问题讨论】:

  • 当前出现错误...那么错误是什么?如果迁移和播种并行运行,您希望它们如何工作?这几乎肯定会破坏事情。

标签: c# entity-framework-core


【解决方案1】:

无论如何,它的价值 migrations 不使用 EnsureCreatedAsync 运行,它在 EFCore 的文档中以真正的大粗体字母显示,也可以在你的种子方法中绕过这个运行 EnsureDeletedAsync(无论如何测试对吗?)。然后运行Database.MigrateAsync();

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#applying-migrations-at-runtime

所以……

编辑

//example method
public void Seed(IApplicationBuilder app)
{
     using(var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
     {
        var context = servicescope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        context.Database.Migrate();
         if(!context.SomeTable.Any()){
            foreach(var item in SeedData.Items){
              context.SomeTable.Add(item);
            }
            context.SaveChanges();
         }

        //for each table you need seeded data...
        //...
     }
}

【讨论】:

  • 谢谢。如果数据库存在,我不希望数据库被删除。我希望这个种子仅在迁移到新数据库时运行。
  • 然后不要运行 delete 方法,但是 migrate 调用是唯一的方法,而不是在命令行上运行命令来获取迁移。如果是新的 dB,则使用 if(!_context.SomeTable.Any()) 循环通过种子数据进行检查,例如
  • 使用 if(!_context.SomeTable.Any()) 将在所有迁移脚本执行时调用?我的理解是从 pmc -> update-database 执行,所有迁移将应用于新数据库,并调用种子数据。对吗?
  • 是的,这是假设没有数据,即新数据库。种子只需要运行一次,但如果存在,迁移将运行。添加新表然后添加更多
  • 例如编辑。
猜你喜欢
  • 2022-01-07
  • 2016-09-17
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 2017-08-13
  • 2020-03-09
  • 2018-07-13
相关资源
最近更新 更多