ObjectDisposedException: Cannot access a disposed object

I am working on this application using In-Memory Cache feature in Asp.Net Core and got this error below.
I have dealt with this error multiple times before and it can be hard to debug sometimes because the cause could be different every time. In this one, I was caching some data that way I did not have to keep going to the database every request. To keep this short, I am going to show the piece of code that was causing the issue below.

Problem

As you can see the category object in code below was an IEnumerable type.


viewModelInfo.Categories = _repository.GetAllCategories().Where(x => x.Businesses.Count > 0).Select(x => new SelectListItem
{
Value = x.Name.ToString(),
Text = x.Name
});

“ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: ‘ApplicationDbContext’.”

Solution

Because of lazy-loading here, the query is not fully executed on the linq statement line. Therefore, adding .ToList() will force it to loop through and generate the category list needed.

Just as the error stated, I verify the ApplicationDbContext making sure Dispose() is not being called in there. Then, I place some breakpoints in the action in the controller and step through until I found the cause of my issue. Below is the final piece of code with the fix.


viewModelInfo.Categories = _repository.GetAllCategories().Where(x => x.Businesses.Count > 0).Select(x => new SelectListItem
{
Value = x.Name.ToString(),
Text = x.Name
}).ToList();