繁体   English   中英

EF Core - 从多个表顺序查询时释放 DbContext

[英]EF Core - DbContext disposed when query from multiple tables sequentially

我有如下代码:

private async void GetCommonInfo(HttpResponse res, MyDbContext db)
{
    long lastUpdated = await db.InfoUpdated.Select(r => r.Common).FirstOrDefaultAsync();
    var info = new CommonInfo
    {
        ARows = await QueryTool.AllIndexByID(db.TableA),
        BRows = await QueryTool.AllIndexByID(db.TableB),
        CRows = await QueryTool.AllIndexByID(db.TableC),
        LastUpdated = lastUpdated,
    };

    await res.WriteAsJsonAsync(info);
}

尽管:

public class QueryTool
{
    public static async Task<Dictionary<int, T>> AllIndexByID<T>(DbSet<T> dbSet)
        where T : class, ITableModel
    {
        return (await dbSet.AsNoTracking().ToListAsync()).ToDictionary(b => b.ID, b => b);
    }
}

当我调用这个方法时,我得到了这个异常:

fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'ApiServer.Models.MyDbContext'.
      System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
      Object name: 'MyDbContext'.
         at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
         at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
         at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Internal.IDbContextDependencies.get_StateManager()
         at Microsoft.EntityFrameworkCore.Query.QueryContextDependencies.get_StateManager()
         at Microsoft.EntityFrameworkCore.Query.QueryContext.InitializeStateManager(Boolean standAlone)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

看起来依赖注入的DbContext只能用于一个查询,然后将其释放。

如果可以,我如何通过使用同步方法或将四个查询集成到一个查询中来解决这个问题,不使用依赖注入或其他方法?

你的问题是async void

替换为async Task并且不要忘记等待GetCommonInfo

附加信息: 异步/等待 - 何时返回任务与无效?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM