【发布时间】:2019-09-10 12:24:04
【问题描述】:
我想使用 EF Core 执行数据库查询。 GetAvailableUsers 方法在.Where(...) 条件中调用另一个方法,该方法也访问DbContext。当我这样做时,我收到以下错误:
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, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations.
FirstService.cs
private MyDbContext _dbContext;
private ISecondService _secondService;
public class FirstService(MyDbContext dbContext, ISecondService secondService)
{
_dbContext = dbContext;
_secondService = secondService;
}
public async Task<List<AppUser>> GetAvailableUsers()
{
return await _dbContext.AppUser
.Where(x => x.IsActive)
.Where(x => _secondService.HasRole(x.Id, 3))
.ToListAsync();
}
SecondService.cs
private MyDbContext _dbContext;
public class SecondService(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public bool HasRole(int userId, int roleId)
{
// ... some complex logic
return _dbContext.AppUserRoles
.Any(x => x.UserId == userId && x.RoleId == roleId);
}
我在 Startup.cs 中注册了 DbContext:
services.AddEntityFrameworkNpgsql().AddDbContext<DbContext>(options => options.UseNpgsql(Configuration.GetConnectionString("abc")));
我怎样才能摆脱错误?是否有任何解决方法可以达到相同的结果?如果我将 DbContext 注册为瞬态会有什么后果?
【问题讨论】:
-
从你的代码中,你想得到所有拥有
roleId=3和IsActive=true的用户吗?你是如何定义你的模型的?它们之间的关系是什么?
标签: c# entity-framework asp.net-core