AymenDaoudi
AymenDaoudi

Reputation: 8309

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

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 :

enter image description here

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;
}

Upvotes: 3

Views: 4770

Answers (1)

i3arnon
i3arnon

Reputation: 116636

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();
     }
}

Upvotes: 10

Related Questions