TL;DR: Don’t return task before disposing context, await it instead
If you’re getting an Entity Framework exception:
System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
at System.Data.Entity.Core.Objects.ObjectContext.ReleaseConnection()
at System.Data.Entity.Core.Objects.ObjectContext.d__3d`1.MoveNext()
— End of stack trace from previous location where exception was thrown —
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Data.Entity.Core.Objects.ObjectContext.d__39.MoveNext()
in the code such as this:
public Task<Order> GetOrders()
{
using (var dbContext = new MyDbContext(connectionString))
{
return dbContext.Orders.ToArrayAsync();
}
}
then it means that you’re disposing the context before the task is completed. Await it, indeed:
public async Task<Order> GetOrders()
{
using (var dbContext = new MyDbContext(connectionString))
{
return await dbContext.Orders.ToArrayAsync();
}
}
Happy awaiting!