ToListAsync() in a DbContext using statement : "The ObjectContext disposed", How to deal?

async-await, asynchronous, c#, entity-framework, linq

Solution

You're leaving the `using` scope before the `ToListAsync` operation completes because you're not awaiting the asynchronous task, which means `entities` is disposed too soon (hence the object disposed exception).

You should just return the result while inside the scope and the `async-await` mechanism will make sure `Dispose` is called after the operation completes asynchronously:

private async Task<List<String>> GetEntiteesAsync()
{
     using (var entities = new REPORTEntities())
     {
          return await (from user in entities.USERs
                         group user by user.entite into g
                               select g.Key).ToListAsync();
     }
}

Problem

I'm trying to get a linq query result using `.ToListAsync()` Inside a using statement of the DbContext, code : ``` private async Task<List<String>> GetEntiteesAsync() { Task<List<String>> returnValue; using (var entities = new REPORTEntities()) { returnValue = (from user in entities.USERs group user by user.entite into g select g.Key).ToListAsync(); } return await returnValue; } ``` when running I get the "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection." as shown : I suppose that this is caused by the fact that the Context was disposed while the returnValue object was still receiving the objects asynchronously as a List, Is there a workaround to avoid this error while keeping the using statement, or I should just go by doing : ``` private async Task<List<String>> GetEntiteesAsync() { Task<List<String>> returnValue; var entities = new REPORTEntities() returnValue = (from user in entities.USERs group user by user.entite into g select g.Key).ToListAsync(); return await returnValue; } ```

Original source