ASP.NET Core 3.1 InvalidOperationException:在上一个操作完成之前在此上下文中启动了第二个操作

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

我在 asp.net 核心 3.1 中使用 _context.savechanges() 或使用存储库时遇到一些问题。

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.

此处显示在浏览器中的更多信息,

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");

我的资料库

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);
    }
}

我的 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.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
        //start Repo
        services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
        services.AddTransient<ICategoryRepository, CategoryRepository>();

任何人,请帮助我。它工作正常。在我使用事务使用 multip SaveChanges 方法之前。现在我回到我以前的代码,我只使用了一个 savechanges() 。之后我收到此错误 =>(第二个操作开始...)。

我可能认为这是由于 Async 和 Await 造成的。我之前也遇到过同样的问题,但我忘记了我为此做了什么。如果可行,请尝试使用同步方法。

您是否尝试使用 ServiceLifetime.Transient

在 startup.cs - ConfigureServices - 配置数据库上下文时

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);

我在控制台应用程序上遇到了同样的问题,并尝试了几个建议,包括异步和等待,但 none 奏效了。

最后我在添加一个实体后添加了一个延迟并且成功了。

                var entity = _context.Contracts.Add(contract_);
                System.Threading.Thread.Sleep(4000);//delay
                var afftected =  _context.SaveChanges();