【问题标题】:Exception The connection's current state is broken when using entity framework异常使用实体框架时连接的当前状态断开
【发布时间】:2012-01-28 11:43:14
【问题描述】:

我对 EF 很陌生...目前我正在使用 EF 在 asp.net 中开发一个网站,但有时我会遇到连接异常。

我读过这篇文章https://github.com/geersch/EntityFrameworkObjectContext根据这个我已经编程了:

public static class ObjectContextPerHttpRequest
{
    public static tradeEntities Context
    {
        get
        {
            string objectContextKey = HttpContext.Current.GetHashCode().ToString("x");
            if (!HttpContext.Current.Items.Contains(objectContextKey))
            {
                HttpContext.Current.Items.Add(objectContextKey, new tradeEntities());
            }
            return HttpContext.Current.Items[objectContextKey] as tradeEntities;
        }
    }
}

然后我使用myEntities et = p.ObjectContextPerHttpRequest.Context;

我需要在我网站上的某个地方获取产品...为了做到这一点,我使用了这个:

    public List<tProducts> returnProductsFromSubcategory(int subcategoryID)
    {
        var prod = from p in et.tProducts
                   from c in et.tCompany
                   where (c.companyID == p.fk_companyID && c.enable == true)
                   where (p.subCategoryID == subcategoryID && p.enable == true)
                   select p;

        //et.Connection.Close();

        return prod.ToList(); //Here comes an Exception The connection's current state is broken.
    }

有时它可以正常工作,但有时我会遇到异常。

System.InvalidOperationException 执行命令需要 开放和可用的连接。连接的当前状态是 坏了。

我不确定出了什么问题。我读过我应该实现 dispose 函数,但是在哪里添加它,我该怎么做呢?

非常感谢您的帮助。

马丁

【问题讨论】:

  • 一旦不再需要查询数据库,您必须在每次使用它的请求处理中处理 ObjectContext。这就是为什么这种使用静态上下文访问器的方法不是很有用的原因。
  • OK,怎么处理?我可以以某种方式动态地做到这一点吗?
  • Ups...看来我的问题已被遗忘...我将非常感谢任何提示我如何编程处置操作。谢谢。

标签: c# asp.net entity-framework linq-to-entities


【解决方案1】:

要处理对象上下文,您应该将查询包装在 using 语句中。

public List<tProducts> returnProductsFromSubcategory(int subcategoryID) 
{ 
    using(var et = new tradeEntities())
    {
        var prod = from p in et.tProducts 
                   from c in et.tCompany 
                   where (c.companyID == p.fk_companyID && c.enable == true) 
                   where (p.subCategoryID == subcategoryID && p.enable == true) 
                   select p; 
        return prod.ToList(); 
    }    
} 

这将自动释放对象上下文并正确关闭与数据库的连接,使其返回连接池。我建议将您的所有查询包装在 using 块中。

【讨论】:

    【解决方案2】:

    你必须处理你的上下文。您可以使用 'using' 运算符,也可以调用 'Dispose' 方法。
    Here 更详细地讨论了该问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2012-09-13
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多