我有這樣的代碼:
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只能用于一個查詢,然后將其丟棄。
如果我能夠,不使用依賴注入或其他方式,我如何通過使用同步方法或將四個查詢集成到一個查詢中來解決這個問題?
uj5u.com熱心網友回復:
你的問題是async void。
替換為async Task,不要忘記 await GetCommonInfo。
附加資訊:async/await - 何時回傳 Task 與 void?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391166.html
上一篇:無法翻譯自定義Linq方法
