Search code examples
multithreadingasync-awaitdbcontextasp.net-core-3.1

ASP.NET Core 3.1 InvalidOperationException: A second operation started on this context before a previous operation completed


I facing some problems in asp.net core 3.1 when using _context.savechanges() or use repository.

InvalidOperationException: 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. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

Here more information the appear in the browser,

if (bill_VM.Custoemr_selected != null)
{
    custId = bill_VM.Custoemr_selected.Id != 0 ? bill_VM.Custoemr_selected.Id : 0;
    _shoppingCart.AddCust(custId);
}
//var selectedItem = await  _context.Items.Where(p => p.Id == itemId).FirstOrDefaultAsync();
var selectedItem = _itemRepository.GetById(itemId); < ---this point
if (selectedItem != null)
{
    _shoppingCart.AddToCart(selectedItem, itemQty, AdjPrice, userid);
}
return RedirectToAction("SalesIndex", "Sales");

my repository

public class Repository<T> : IRepository<T> where T : class
{
    protected readonly ApplicationDbContext _context;
    public Repository(ApplicationDbContext context)
    {
        _context = context;
    }
    protected void Save() => _context.SaveChanges();
    protected async Task<int> SaveAsync() => await _context.SaveChangesAsync();
          ........ // some get and create methods are here
            public T GetById(int Id)
    {
        return _context.Set<T>().Find(Id);
    }
    private bool disposed = false;
    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

My ApplicationDbContext

     public class ApplicationDbContext : IdentityDbContext
    {

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<ApplicationUser> ApplicationUsers { get; set; }
        public DbSet<ApplicationRole> ApplicationRoles { get; set; }
        ....... // DbSet
}

services

 services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        //start Repo
        services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
        services.AddTransient<ICategoryRepository, CategoryRepository>();

anyone, please help me. It was working properly. before I using the multip SaveChanges method using transaction. now I come back to my previous code which only I Used one savechanges() . after that I receive this error => (A second operation started...).

  • =>any async-await problem ...? or
  • =>not clearly Dispose() my dbcontext...? or
  • =>need to add any service ..?

Solution

  • I probably believe it is due to Async and Await. I had also faced the same issue earlier but I forgot what I did for this. Try with synchronous approach if it works.