我似乎找不到这个问题的答案。
因此在前端,当用户加载页面时,我们会为该页面上的每个项目(10 个项目)调用一个 API。所以这等于 10 个 API 调用。
大多数调用都有效,但在尝试查询数据库时总会有一些调用失败,导致以下错误:
InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
现在我明白 Entity Framework 不是线程安全的,但我不确定如何解决这个错误。
在我使用 DBContext 的任何地方,它总是使用内置的 .net 核心 Ioc 容器注入(inject)。
这是DI设置
services.AddScoped<IOmbiContext, OmbiContext>();
services.AddTransient<ISettingsRepository, SettingsJsonRepository>();
根据本文:https://learn.microsoft.com/en-us/aspnet/core/data/entity-framework-6,我的所有存储库都设置在 Transient
范围内,上下文为 Scoped
现在我尝试将上下文更改为 Transient
,但它仍然发生。
我怎样才能避免这种情况?
更多信息
API 方法:
[HttpGet("movie/info/{theMovieDbId}")]
public async Task<SearchMovieViewModel> GetExtraMovieInfo(int theMovieDbId)
{
return await MovieEngine.LookupImdbInformation(theMovieDbId);
}
最终会在抛出异常的地方调用以下代码:
public async Task<RuleResult> Execute(SearchViewModel obj)
{
var item = await PlexContentRepository.Get(obj.CustomId); <-- Here
if (item != null)
{
obj.Available = true;
obj.PlexUrl = item.Url;
obj.Quality = item.Quality;
}
return Success();
}
PlexContentRepository
public PlexContentRepository(IOmbiContext db)
{
Db = db;
}
private IOmbiContext Db { get; }
public async Task<PlexContent> Get(string providerId)
{
return await Db.PlexContent.FirstOrDefaultAsync(x => x.ProviderId == providerId); <-- Here
}
最佳答案
如果您使用 Entity Framework Core,通常不需要将数据库上下文添加为附加服务
我建议在 Startup.cs
中设置您的 DbContext,如下所示:
services.AddEntityFrameworkSqlServer()
.AddDbContext<OmbiContext>();
随后是一个 Controller 类,用于您的 API 调用,将 DBContext 作为构造函数参数。
public class ApiController : Controller
{
protected OmbiContext ctx;
public ApiController(OmbiContext dbctx)
{
ctx = dbctx;
}
public async Task<IActionResult> yourAsyncAction()
{
// access ctx here
}
}
关于c# - EF Core 多个 HTTP 请求抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45881718/