pr1*_*177 8 c# entity-framework-core asp.net-core asp.net-core-3.0 entity-framework-core-3.0
我有一个 ASP.NET Core 2.2 WebApi 项目,它也使用 EF Core 2.2。该项目通过集成测试与WebApplicationFactory<T>.
我尝试将 web api 项目迁移到 netcore/aspnetcore 3,效果很好。我偶然发现的是迁移测试。
我有以下在 aspnetcore 2.2 中工作的代码:
public class MyServiceWebHostFactory : WebApplicationFactory<Service.Startup>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
services.AddDbContext<MyContext>((options, context) =>
{
context.UseInMemoryDatabase("MyDb")
.UseInternalServiceProvider(serviceProvider);
});
var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
var scopedServices = scope.ServiceProvider;
// try to receive context with inmemory provider:
var db = scopedServices.GetRequiredService<MyContext>();
// more code...
// Ensure the database is created.
//db.Database.EnsureCreated();
// more code...
});
}
}
Run Code Online (Sandbox Code Playgroud)
它使用 InMemoryProvider 将 EF Core DbContext 替换为 DbContext。
迁移到 3.0 后,它不再被替换。我总是收到配置了 SQL Server 的 DBContext。
如果我删除应用程序 ( )的services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString))调用,它会起作用,但这不是解决方案。ConfigureServicesService.Startup
services.RemoveAll(typeof(MyContext))在注册也不起作用的内存上下文之前,我也尝试过。
eug*_*ecp 16
https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1 上的更新文档可能会有所帮助。关键片段变化是去掉之前的上下文服务注册:
// Remove the app's ApplicationDbContext registration.
var descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<ApplicationDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// Add ApplicationDbContext using an in-memory database for testing.
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
});
// Build the service provider.
var sp = services.BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3282 次 |
| 最近记录: |