Multiple EF Core HTTP requests cause an error

It seems I can not find the answer to this question.

So, in the interface, when the user loads the page, we call the API for each element on this page (10 elements). Thus, this equals 10 API calls.

Most calls work, but when you try to query the database, some errors always occur that lead to the following error:

InvalidOperationException: The second operation started from this context until the previous operation completed. Any instance members do not guarantee thread safety.

Now I understand that the Entity Framework is not thread safe, but I'm not sure how to get around this error.

Wherever I use DBContext, it is always entered when using the built-in IOC kernel .net container.

Here is the DI setting

services.AddScoped<IOmbiContext, OmbiContext>(); services.AddTransient<ISettingsRepository, SettingsJsonRepository>(); 

All my repositories are configured in the Transient scope with Context as Scoped according to this article: https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6

Now I tried changing the context to Transient , and this will happen anyway.

How can i avoid this?

Additional Information

API Method:

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

In the end, the following is raised where the exception is thrown:

 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 } 
+5
source share
1 answer

If you are using Entity Framework Core, you usually do not need to add your database context as an additional service.

I recommend setting up DbContext in Startup.cs as follows:

 services.AddEntityFrameworkSqlServer() .AddDbContext<OmbiContext>(); 

The following is the Controller class for your API calls, taking DBContext as the constructor parameter.

 public class ApiController : Controller { protected OmbiContext ctx; public ApiController(OmbiContext dbctx) { ctx = dbctx; } public async Task<IActionResult> yourAsyncAction() { // access ctx here } } 
-2
source

Source: https://habr.com/ru/post/1271230/


All Articles