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

问题描述 投票:0回答:2

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

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()。之后,我收到此错误=>(开始第二次操作...)。

  • =>任何异步等待问题...?或
  • =>不清楚Dispose()我的dbcontext ...?或
  • =>需要添加任何服务..?
multithreading async-await dbcontext asp.net-core-3.1
2个回答
0
投票

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


0
投票

您尝试使用ServiceLifetime.Transient

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

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
© www.soinside.com 2019 - 2024. All rights reserved.