【问题标题】:DbContext has been disposed (ASP.NET MVC) [duplicate]DbContext 已被处置(ASP.NET MVC)[重复]
【发布时间】:2017-10-02 11:13:21
【问题描述】:

我有 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

我该如何解决这个错误?

【问题讨论】:

  • 嗯。似乎是的。我制作了return ctx.Sites.ToList();,现在它运行良好@Marisa

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


【解决方案1】:

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

【讨论】:

  • 非常感谢您的回答
  • @ЕвгенийСухомлин 不客气
【解决方案2】:

IEnumerable 类需要活动上下文才能执行其操作。

类型为IQueryable&lt;T&gt;IEnumerable&lt;T&gt; 的对象实际上不会“执行”,直到它们被迭代或以其他方式访问,例如组合成List&lt;T&gt;

只需使用.ToList 方法。

 return ctx.Sites.ToList();

【讨论】:

  • 是的。我明白了,但我也可以在 repo 方法中制作 .ToList 吗?
  • 是的,您可以,但请保留在当前代码中。将来,您可能需要对某些字段使用GetSites 方法过滤,对IQueryable 数据进行这些过滤会更有效。
  • 嗯。将代码粘贴到 Global.asax 文件中,仍然出现此错误。如果我在方法中编写 .ToList,网站运行良好。
  • @ЕвгенийСухомлин,是的,在 repo 中复制。
  • @ЕвгенийСухомлин,对不起,我的错误我认为你从 repo 返回了 IQeuryable,但你返回了 IEnumerable
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-22
  • 2017-03-19
  • 2014-02-08
  • 1970-01-01
相关资源
最近更新 更多