已经处理了DbContext(ASP.NET MVC)

时间:2017-10-02 11:13:22

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

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

当我运行网站时,我有这个错误

  

由于已经处理了DbContext,因此无法完成操作。

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

如何解决此错误?

2 个答案:

答案 0 :(得分:2)

IEnumerable课程需要有效上下文才能执行其操作。

类型为IQueryable<T>IEnumerable<T>的对象在迭代或以其他方式访问之前实际上并不“执行”,例如被组合成List<T>

只需使用.ToList方法。

 return ctx.Sites.ToList();

答案 1 :(得分:2)

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

你可以在你的方法GetSites()中看到dbContext在返回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();
    }
}