Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make parallel async queries in EF Core 3.0 with repository pattern?

I have repository like

public interface IEmployeeRepository
{
  Task<EmployeeSettings> GetEmployeeSettings(int employeeId);
  Task<ICollection<DepartmentWorkPosition>> GetWorkPositions(int employeeId);
}

Constructor of repository (DbContext injection):

public EmployeeRepository(EmployeeDbContext dbContext)
{
  _dbContext = dbContext;
}

And call it in EF Core 2.0 like

var settingsTask = _employeeRepository
    .GetEmployeeSettings(employeeId.Value);

var workPositionsTask = _employeeRepository
    .GetWorkPositions(employeeId.Value);

await Task.WhenAll(settingsTask, workPositionsTask);

// do other things...

Problem:

With EF Core 3.0 there is InvalidOperationException: a second operation started on this context before a previous operation completed...

DbContext is registered in ConfigureServices like

services.AddDbContext<EmployeeDbContext>(ServiceLifetime.Transient);

Tutorial says following: Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.

But! How to use it with repositories in async?

like image 769
Arsync Avatar asked Nov 16 '22 00:11

Arsync


1 Answers

How to use it with repositories in async?

You can only have one simultaneous asynchronous request per repository. If you need to have more than one at a time, then you need more than one repository. This may require you to inject a repository factory into your types.

like image 194
Stephen Cleary Avatar answered Dec 10 '22 18:12

Stephen Cleary