我知道這裏有一堆這樣的錯誤消息,因爲我已經閱讀了所有這些錯誤消息,可惜無濟於事。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()
錯誤告訴我,別的東西正在努力讀書,上下文的使用條款已彈出後,但我茫然地知道,可能是什麼?正如你所看到的,我將枚舉數據從上下文複製到本地列表中,然後再返回。給我塞了!
任何建議表示讚賞。
嘗試在此行末尾添加'.ToList()'persons = entities.Persons.Take(5)'並看看會發生什麼 –
確實。 'IEnumerable <>'表示延遲執行。這個看似無關的[問題](http://stackoverflow.com/q/36828822/60761)處理同樣的問題。 –