DbContext 已被释放(ASP.NET MVC)

DbContext has been disposed (ASP.NET MVC)

我有 GeneralRepository

这是代码

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


}

在 Global.asax 中,我有这段代码使用 repo 和 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);
    }

当我 运行 网站出现此错误

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

在这一行 var siteDictionary = repository.GetSites().ToDictionary

如何解决这个错误?

IEnumerable class 需要 active 上下文才能执行其操作。

类型为 IQueryable<T>IEnumerable<T> 的对象实际上并不 "execute" 直到它们被迭代或以其他方式访问,例如被组合成 List<T> .

只需使用.ToList方法。

 return ctx.Sites.ToList();

方法 GeneralRepository.GetSites() return 是一个 IQueryable,而 IQueryable 不会 return 任何结果,它只是定义查询表达式,任何结果都不会是 return 直到您执行该查询(例如通过调用 linq 方法)。

并且您可以在方法 GetSites() 中看到,dbContext 是在 returning IQueryable 对象(这只是一个查询定义)之后处理的

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

所以要解决你的问题,只需改变你的方法如下:

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