【发布时间】:2022-02-04 21:31:47
【问题描述】:
在使用 _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>();
任何人,请帮助我。它工作正常。在我使用事务的多重 SaveChanges 方法之前。现在我回到我之前的代码,我只使用了一个 savechanges() 。之后我收到此错误 =>(第二个操作开始...)。
- =>任何异步等待问题...?或
- =>不清楚 Dispose() 我的 dbcontext...?或
- =>需要添加任何服务..?
【问题讨论】:
-
你能发布异常的堆栈跟踪吗?你能说明
ApplicationDbContext是如何创建的吗? -
@PauloMorgado
public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<ApplicationUser> ApplicationUsers { get; set; } public DbSet<ApplicationRole> ApplicationRoles { get; set; } ........ } } -
我们仍然不知道实例是如何被提供给
Repository<T>的构造函数的。 -
@Paulo 我应该通过存储库传递 T 吗?能解释清楚吗?
-
我们需要知道异常的完整堆栈跟踪以及
ApplicationDbContext是如何被实例化的以便能够提供帮助。
标签: multithreading async-await dbcontext asp.net-core-3.1