I have run two Async methods using Entity Framework 2.1 - one for selecting the total count and another for retrieving page data - and I marked my entity AsNoTracking as following:
var dbContext = new SamuraiAppDataCoreContext();
var query = dbContext.Samurais.AsNoTracking();
var pageQuery = query.Skip(0).Take(10);
var totalCountTask = query.CountAsync();
var pageRecordsTask = pageQuery.ToListAsync();
await Task.WhenAll(totalCountTask, pageRecordsTask);
var results = new { TotalCount = totalCountTask.Result, Pages = pageRecordsTask.Result };
Then I got the following error
InvalidOperationException: The connection was not closed. The connection's current state is connecting. System.Data.ProviderBase.DbConnectionClosedConnecting.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource retry, DbConnectionOptions userOptions
Notes: the error goes away in following scenarios
using await for each Async
var totalCount = await query.CountAsync();
var pageRecords = await pageQuery.ToListAsync();
And my question is:
why AsNoTracking is not working with multi-Async calls?
Had exactly the same problem, after some research I found the same answer as what @CamiloTerevinto said.
EF Core does not support multiple parallel operations being run on the same context instance. You should always wait for an operation to complete before beginning the next operation. This is typically done by using the await keyword on each asynchronous operation.
https://docs.microsoft.com/en-us/ef/core/querying/async
So the solution is to create a context instance for each query, like in the example here https://riptutorial.com/entity-framework/example/13437/execute-multiple-queries-async-and-in-parallel