.NET中DbContext多线程并发报错原因咨询(原.NET5无此问题)
DbContext多线程并发访问报错问题
我在系统中遇到了报错,错误提示如下:
"This is usually caused by different threads concurrently using the same instance of DbContext"
此前在.NET 5环境下并未出现此类错误,而且我在API开发中从来没碰到过这个问题。我刚接触async方法,现在附上相关C#代码(代码里用了AsQueryable做后续过滤),希望有人能帮忙解惑。
相关代码:
private DataContext _Context; private IFileUpload _File; public ProductRepository(DataContext Context, IFileUpload file) : base(Context) { _Context = Context; _File = file; } public async Task<Product> GetProductByUrl(string ProductUrl, bool tracking = false) { var Model = _Context.Products .Include(i => i.ProductPictures) .Include(i => i.MyProperty) .ThenInclude(i => i.Category) .AsQueryable(); if (!tracking) { Model = Model.AsNoTracking(); } return await Model.FirstOrDefaultAsync(i => i.Url == ProductUrl); }
内容的提问来源于stack exchange,提问作者Mehmet kelleli
相关产品推荐
相关产品推荐

