gpt4 book ai didi

c# - ASP.NET Core 集成测试 UseLazyLoadingProxies 需要在使用的内部服务提供者上调用 AddEntityFrameworkProxies

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:12 32 4
gpt4 key购买 nike

我正在构建 Web 服务并尝试实现一些集成测试,但在运行测试时我看到以下错误;

UseLazyLoadingProxies requires AddEntityFrameworkProxies to be called on the internal service provider used.

谷歌没有为这个错误提供任何有用的结果,我不知道如何解决它。我已尝试将 services.AddEntityFrameworkProxies() 添加到我的 Startup.cs 文件和我的测试项目中的 CustomWebApplicationFactory.cs 文件。都没有解决问题。

这是 IntegrationTests 项目中我的 CustomWebApplicationaFactory.cs 文件;

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// Create a new service provider.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();

// Add a database context (AppDbContext) using an in-memory database for testing.
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseLazyLoadingProxies();
options.UseInMemoryDatabase("InMemoryAppDb");
options.UseInternalServiceProvider(serviceProvider);
});

// Add a database context (AppDbContext) using an in-memory database for testing.
services.AddDbContext<MultiTenantDbContext>(options =>
{
options.UseLazyLoadingProxies();
options.UseInMemoryDatabase("MultiTenantInMemoryAppDb");
options.UseInternalServiceProvider(serviceProvider);
});

// Build the service provider.
var sp = services.BuildServiceProvider();

// Create a scope to obtain a reference to the database contexts
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var appDb = scopedServices.GetRequiredService<ApplicationDbContext>();

var logger = scopedServices.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();

// Ensure the database is created.
appDb.Database.EnsureCreated();

try
{
// Seed the database with some specific test data.
SeedData.PopulateTestData(appDb);
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred seeding the " +
"database with test messages. Error: {ex.Message}");
}
}
});
}
}

最佳答案

我按照错误告诉我的方式解决了这个问题。我向服务提供者添加了 AddEntityFrameworkProxies()

// Create a new service provider.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.AddEntityFrameworkProxies()
.BuildServiceProvider();

关于c# - ASP.NET Core 集成测试 UseLazyLoadingProxies 需要在使用的内部服务提供者上调用 AddEntityFrameworkProxies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57302595/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com