ASP.NET (C#) Question

DbContext has been disposed (ASP.NET MVC)

I have GeneralRepository

Here is code

public class GeneralRepository
{



public IEnumerable<Site> GetSites()
{
using (TraxgoDB ctx = new TraxgoDB())
{
return ctx.Sites;
}
}

public Customer GetCustomer(int customerID, bool main = false)
{
using (TraxgoDB ctx = new TraxgoDB())
{
var customer = ctx.Customers.First(c => c.ID == customerID);
if (main) customer = (customer as SubUser)?.MainUser ?? customer;

return customer;
}
}
public Dictionary<int,int> GetCustomerIDDictionary()
{
using (TraxgoDB ctx = new TraxgoDB())
{
return ctx.Customers.ToDictionary(
c => c.ID,
c => (c as SubUser) != null ? (int) (c as SubUser).MainUserID : c.ID
);
}
}


}


In Global.asax i have this code that using repo and method from repo

private ConcurrentDictionary<string, SiteViewModel> InitializeSites()
{
var repository = new GeneralRepository();
var siteDictionary = repository.GetSites().ToDictionary(
s => s.HostName.ToLower(),
s => SiteViewModel.CreateCustomTrackerwebSite(s.HostName, s)
);

return new ConcurrentDictionary<string, SiteViewModel>(siteDictionary);
}


When I run website I have this error


The operation cannot be completed because the DbContext has been disposed.


In this row
var siteDictionary = repository.GetSites().ToDictionary


How I can solve this error?

Answer Source

The method GeneralRepository.GetSites() returns a IQueryable, and IQueryable doesn't return any result, it just define the query expressions, and any result won't be return untill you execute that query (by calling a linq method for example).

And you can see in your method GetSites() that the dbContext is disposed just after returning the IQueryable Object (Which is just a query definition)

public IEnumerable<Site> GetSites()
{
    using (TraxgoDB ctx = new TraxgoDB())
    {
        return ctx.Sites;
    }
}

So to solve your problem, just change your method like below:

public IEnumerable<Site> GetSites()
{
    using (TraxgoDB ctx = new TraxgoDB())
    {
        return ctx.Sites.ToList();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download