SB2055
SB2055

Reputation: 12852

Await is disposing DbContext - The ObjectContext instance has been disposed

I have the following in an async method that has an instance of dbContext passed into it:

 var userIds = await GetUserIds(db);

With GetUserIds:

    private async Task<List<int>> GetUserIds(AppContext db)
    {
        var items = await db.Items.Where(s => s.IsValid).Distinct().ToListAsync(); // simplified
        return items;
    }

But I get:

{"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."}

I can force this to run by removing await and ToListAsync, but obviously that's just a bandaid. Why is my context getting disposed?

Upvotes: 0

Views: 789

Answers (1)

Drew Noakes
Drew Noakes

Reputation: 310792

I suspect the caller of your GetUserIds method is disposing the context before the operation completes. Are you sure you're awaiting the returned Task before disposing the context?

Upvotes: 3

Related Questions