You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:01:28