[英]'The operation cannot be completed because the DbContext has been disposed.'
[英]EF6 The operation cannot be completed because the DbContext has been disposed
我知道在SO中有一堆這些錯誤消息,因為我已經全部讀過它們,遺憾的是無濟於事。
我有一個WebApi控制器,通過EF6從SQL Server數據庫獲取一組“人員”。 很簡單的例子
到目前為止我嘗試過的事情沒有成功: - 禁用代理生成 - 禁用延遲加載 - 添加包含以獲取具有linq和字符串參數的子引用。 - 用try / finally替換使用 - >處理DbContext。 - 通過WebApiConfig從支持的媒體類型中刪除“application / 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()
錯誤告訴我其他東西試圖在使用子句彈出后讀取上下文但是我不知道那可能是什么? 如您所見,我在返回之前將枚舉數據從上下文復制到本地列表中。 讓我塞滿了!
任何建議贊賞。
這條線
persons = entities.Persons.Take(5);
是如何檢索數據的定義,但此時尚未檢索到數據本身(“延遲執行”)。 該行位於using(){}
構造內部,因此在此之后處理DbContext
。 稍后View需要數據,請咨詢DbContext,但它已經關閉了。
解:
在關閉DbContext之前檢索所有數據。 這通常使用ToArray()
或ToList()
,無論哪個最適合您。
所以該行應該是例如:
persons = entities.Persons.Take(5).ToArray();
persons = entities.Persons.Take(5).ToList()
或ToArray
。
實際上,您在獲取數據之前關閉了連接。
如果這不起作用,請嘗試刪除dbcontext
using
子句,以檢查發生了什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.