'How to use DbContext in a foreach loop asynchronously

As far as I understand DBContext does not support multiple parallel operations, so we use await async calls or use of separate DBContext instances are needed to execute in parallel.

From research, I'm properly using foreach/ await to make asynchronous calls which I'm fine with. I'm trying to understand why I'm getting the following error:

 A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DBContext.

This is my code:

public async Task<Obj> GetOrdersFromTable(List<int> dates)
{
   foreach(var date in dates)
      var data = await _repository.GetOrderAsync(date)
}

public async Task<Obj> GetOrderAsync(DateTime date)
{
   var orders = await _dbContext.Where(...).FirstOrDefaultAsync()
}

How can I properly use DbContext in a foreach loop asynchronously? Currently I see the container is registered by default.

Would it be more proper use Reusescope.None or ReuseScope.Request?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source