我得到了这个错误:"System. InvalidOperationException:'在上一个操作完成之前,在此上下文实例上启动了第二个操作.这通常是由不同线程并发使用同一个DbContext实例造成的.
这是我的服务代码:
public async Task<IQueryable<GetAllUsersDTO>> UsersById(Guid userId, CancellationToken cancellationToken)
{
try
{
var Log = await _db.Users
.Include(x => x.University)
.Include(x => x.Fields)
.Where(x => x.UserId == userId)
.OrderByDescending(x => x.CreatedAt)
.AsNoTracking()
.ToListAsync();
var logsDTO = await Task.WhenAll(Log.Select(async x =>
{
var userInDb = await _db.Users.FindAsync((Guid)x.UserId);
var user = await _userService.GetDirectoryInformation(userInDb, cancellationToken);
return new GetAllUsersDTO()
{
Description = x.Description,
PostDate = x.PostDate,
Id = x.Id,
RecieveUserId = x.RecieveUserId,
UniversityId = x.UniversityId,
IsVisible = x.IsVisible,
IsApproved = x.IsApproved,
UserIdOpen = x.UserId,
UserName = user.UserName,
LogTitle = x.LogTitle,
LogNr = x.LogNr,
Email = user.Email,
};
}));
return logsDTO.AsQueryable();
}
catch (Exception ex)
{
Console.WriteLine("Error=", ex.Message);
throw;
}
}
这就是我在这个服务中注入DataContext的方式:
private readonly DataContext _db;
public UserService(DataContext context) : base(context)
{
_db = context;
}
注意:此服务仅在日志(log)列表仅返回一个数据时才起作用.但是当它返回多个数据时,它会触发错误.
我试着用ServiceLifetime.Scoped配置依赖注入设置,结果如下所示:
builder.Services
.AddDbContext<DataContext>(opt =>
opt.UseSqlServer(builder.Configuration.GetConnectionString("connString"))
,ServiceLifetime.Scoped
);