.net core ef 迁移测试 - 使用 c# 方法应用迁移

.net core ef migration testing - apply migrations using c# method

我认为必须测试 ef 迁移。 至于我,集成测试将是最好的解决方案。 当前的解决方案是将迁移应用于内存数据库,但问题是我还想 运行 关闭迁移脚本。

你知道如何使用 C# 代码应用迁移吗?

获取上下文并调用

context.Database.Migrate();

在 Startup.cs 配置方法中,我们 运行 像这样迁移(在 .Net core 2.0 中):

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetService<DataContext>().Database.Migrate();
            }

我不确定您如何测试它。可能将实时数据库备份并恢复到测试数据库,然后将您的 DataContext 设置为指向测试和 运行 那里的迁移?

根据 。我能够找出如何使用 c# 代码中的 ef core 迁移到特定的迁移。

context.Database.EnsureDeleted(); // ensure db is deleted on starting
context.Database.Migrate(); // run migrations
context.GetService<IMigrator>().Migrate("0"); // 0 this will rollback all migrations, you can pass in the specific migration name here to go up or down to that migration

使用命令行 dotnet ef database update 0