I have a simple project which has not update/delete and I insert using dapper library. I use ef core just for fetching data (mostly asNoTracking). Note that
- I use the default scoped DbContext
- I use a full
async
ef repository
Startup.cs
services.AddDbContext<MyContext>(options =>
{
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
});
},
This is one of the methods in my generic repository
public async Task<List<TDto>> GetAsNoTrackingAsync<TDto>(Expression<Func<T, bool>> predicate)
{
return await Context.Set<T>()
.AsNoTracking()
.Where(x => !x.IsDeleted)
.Where(predicate)
.OrderByDescending(e => e.RTime)
.ToListAsync();
}
and how I use it:
var result = await _repository.GetAsNoTrackingAsync<TDto>(e => e.Id == id);
but unfortunately I encounter with the below multithreading issue rarely which is strange for me.
A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
I have searched a lot for this issue, but found no solution except making the DbContext as transient (which I think it is not a solution).
It is not 100% percent reproduciblem but I sometimes I could do so by multiple requesting the request (e.g. clicking on F5 button twice quickly)
Any solution is appreciated.