2016-04-25 66 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只是爲了檢查發生了什麼。

相關問題