2

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?

2 Answers2

2

IEnumerable class requires an active context in order to perform its operations.

Objects with the type as IQueryable<T> and IEnumerable<T> don't actually "execute" until they are iterated over or otherwise accessed, such as being composed into a List<T>.

Just use .ToList method.

 return ctx.Sites.ToList();
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2

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();
    }
}