我知道这里有一堆这样的错误消息,因为我已经阅读了所有这些错误消息,可惜无济于事。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)处理同样的问题。 –