Entity Framework core 2.1 Using AsNoTracking with multiple Async gives InvalidOperationException: The connection was not closed

async-await asynchronous c# entity-framework-core

Question

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

enter image description here

Notes: the error goes away in following scenarios

  1. Removing "AsNoTracking"
  2. 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?

1
0
7/14/2019 7:54:05 PM

Popular Answer

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

0
7/14/2019 7:19:41 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow