问题描述
我有这样的仓库
public interface IEmployeeRepository
{
Task<EmployeeSettings> GetEmployeeSettings(int employeeId);
Task<ICollection<DepartmentWorkPosition>> GetWorkPositions(int employeeId);
}
存储库的构造函数(DbContext 注入):
Constructor of repository (DbContext injection):
public EmployeeRepository(EmployeeDbContext dbContext)
{
_dbContext = dbContext;
}
并在 EF Core 2.0 中调用它
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...
问题:
EF Core 3.0 存在 InvalidOperationException:在上一个操作完成之前,在此上下文上启动了第二个操作...
With EF Core 3.0 there is InvalidOperationException: a second operation started on this context before a previous operation completed...
DbContext 在 ConfigureServices 中注册,例如
DbContext is registered in ConfigureServices like
services.AddDbContext<EmployeeDbContext>(ServiceLifetime.Transient);
教程如下:Entity Framework Core 不支持在同一个 DbContext 实例上运行多个并行操作.
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?
推荐答案
每个存储库只能有一个并发异步请求.如果您需要一次拥有多个,那么您需要多个存储库.这可能需要您将存储库工厂注入您的类型.
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.
这篇关于如何使用存储库模式在 EF Core 3.0 中进行并行异步查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!