2016-04-25 196 views
3

我知道这里有一堆这样的错误消息,因为我已经阅读了所有这些错误消息,可惜无济于事。EF6操作无法完成,因为已经配置了DbContext

我有一个WebApi控制器,通过EF6从SQL Server数据库中获取一组“人员”。很简单的例子

事情我到目前为止已经试过,没有成功: - 禁用代理代 - 禁用延迟加载 - 添加包括让孩子裁判既LINQ和字符串参数。 - 用try/finally替换使用 - >处理DbContext。 - 通过WebApiConfig 从支持的媒体类型中删除 “应用程序/ XML” - 有保证的循环依赖是由于使用[IgnoreDataMember] - ...更多我不记得:)

这里是PersonController Get方法:

public IEnumerable<Person> Get() 
    { 
     try 
     {    
      IEnumerable<Person> persons = null; 
      using (PersonContext entities = new PersonContext()) 
      { 
       entities.Configuration.ProxyCreationEnabled = false; 
       entities.Configuration.LazyLoadingEnabled = false; 
       persons = entities.Persons.Take(5); 
      } 
      return persons; 
     } 
     catch(Exception ex) 
     { 
      ... 
     }    
    } 

现在控制器中的任何点都不会引发异常。然而,异常显示在浏览器:

"<Error><Message>An error has occurred.<\Message> 
<ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application\/json; charset=utf-8'. 
<\ExceptionMessage> 
<ExceptionType>System.InvalidOperationException<\ExceptionType> 
<StackTrace/> 
<InnerException> 
    <Message>An error has occurred.<\/Message> 
    <ExceptionMessage>**The operation cannot be completed because the DbContext has been disposed.**<\/ExceptionMessage> 
    <ExceptionType>System.InvalidOperationException<\/ExceptionType> 
    <StackTrace> at 
     System.Data.Entity.Internal.LazyInternalContext.InitializeContext() 

错误告诉我,别的东西正在努力读书,上下文的使用条款已弹出后,但我茫然地知道,可能是什么?正如你所看到的,我将枚举数据从上下文复制到本地列表中,然后再返回。给我塞了!

任何建议表示赞赏。

+5

尝试在此行末尾添加'.ToList()'persons = entities.Persons.Take(5)'并看看会发生什么 –

+0

确实。 'IEnumerable <>'表示延迟执行。这个看似无关的[问题](http://stackoverflow.com/q/36828822/60761)处理同样的问题。 –

回答

4

线

persons = entities.Persons.Take(5); 

是如何检索数据的定义,但数据本身尚未在该点(“延迟的执行”)检索。该线位于using(){}结构内,因此在此之后DbContext被处置。过了一会儿,视图需要数据,查询了DbContext,但它已经关闭了。

解决方案:
在关闭DbContext之前检索所有数据。这通常使用ToArray()ToList(),以最适合您为准。

所以行应例如为:

persons = entities.Persons.Take(5).ToArray(); 
+0

是的,刚刚发现了这个。哇,我确定Take做了枚举?无论如何,感谢您的快速回复。非常感激。 – ComeIn

1

persons = entities.Persons.Take(5).ToList()ToArray

您实际上在提取数据之前关闭连接。

如果这不起作用,请尝试删除using子句为dbcontext只是为了检查发生了什么。

相关问题