我知道 SO 中有很多这样的错误消息,因为我已经阅读了所有这些错误消息,遗憾的是没有用。
我有一个 WebApi Controller ,它通过 EF6 从 SQL Server 数据库获取一组“人员”。非常简单的例子
到目前为止,我尝试过的事情都没有成功: - 禁用代理生成 - 禁用延迟加载 - 添加包含以获取具有 linq 和字符串参数的子引用。 - 将 using 替换为 try/finally -> 处理 DbContext。 - 通过 WebApiConfig 从支持的媒体类型中删除“application/xml” - 确保循环依赖归因于 [IgnoreDataMember] - ...更多我不记得了:)
这是 PersonController 的获取方法:
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)
{
...
}
}
现在 Controller 中的任何一点都不会抛出异常。但是在浏览器中显示异常:
"<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()
错误告诉我在 using 子句弹出后有其他东西试图读取上下文,但我不知道那可能是什么?如您所见,我在返回之前将上下文中的枚举数据复制到本地列表中。把我塞满了!
任何建议表示赞赏。
最佳答案
线
persons = entities.Persons.Take(5);
是如何检索数据的定义,但此时数据本身尚未检索(“延迟执行”)。该行位于 using(){}
构造内,因此紧接着 DbContext
被释放。一段时间后,View 需要数据,查询 DbContext,但它已经关闭。
解决方法:
在关闭 DbContext 之前检索所有数据。这通常使用 ToArray()
或 ToList()
来完成,以最适合您的方式为准。
所以该行应该是例如:
persons = entities.Persons.Take(5).ToArray();
关于c# - EF6 操作无法完成,因为 DbContext 已被释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36840348/