SB2055 SB2055 - 11 months ago 57
C# Question

Await is disposing DbContext - The ObjectContext instance has been disposed

I have the following in an

method that has an instance of
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
, but obviously that's just a bandaid. Why is my context getting disposed?

Answer Source

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?