EF Core多个HTTP请求引发错误

Jam*_*ees 6 .net c# entity-framework entity-framework-core asp.net-core

我似乎找不到这个问题的答案.

因此,在用户加载页面的前端,我们为该页面上的每个项目调用API(10个项目).这等于10个API调用.

大多数调用都有效,但在尝试查询数据库时总会有一些调用失败,从而导致以下错误:

InvalidOperationException:在上一个操作完成之前,在此上下文中启动了第二个操作.任何实例成员都不保证是线程安全的.

现在我明白Entity Framework不是线程安全的,但我不确定如何解决这个错误.

在我使用DBContext的任何地方,总是使用内置的.net核心Ioc容器注入.

这是DI设置

services.AddScoped<IOmbiContext, OmbiContext>();
services.AddTransient<ISettingsRepository, SettingsJsonRepository>();
Run Code Online (Sandbox Code Playgroud)

根据本文的内容,我的所有存储库都在TransientContext 中设置Scoped:https: //docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6

现在我已经尝试将上下文更改为Transient仍然会发生.

我怎么能避免这个?

更多信息

API方法:

[HttpGet("movie/info/{theMovieDbId}")]
public async Task<SearchMovieViewModel> GetExtraMovieInfo(int theMovieDbId)
{
    return await MovieEngine.LookupImdbInformation(theMovieDbId);
}
Run Code Online (Sandbox Code Playgroud)

最终会调用以下异常抛出的异常:

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();
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

Ole*_*e K -2

如果您使用 Entity Framework Core,通常不需要将数据库上下文添加为附加服务

我建议按如下方式设置 DbContext Startup.cs

services.AddEntityFrameworkSqlServer()
            .AddDbContext<OmbiContext>();
Run Code Online (Sandbox Code Playgroud)

接下来是用于 API 调用的控制器类,将 DBContext 作为构造函数参数。

public class ApiController : Controller
{
    protected OmbiContext ctx;
    public ApiController(OmbiContext dbctx)
    {
        ctx = dbctx;
    }

    public async Task<IActionResult> yourAsyncAction()
    {
        // access ctx here
    }
}
Run Code Online (Sandbox Code Playgroud)