EF6操作已完成,因为已处置DbContext

Com*_*eIn 4 c# sql-server entity-framework asp.net-web-api

我知道SO中有很多这样的错误消息,因为我已经阅读了所有这些错误消息,可惜没有用。

我有一个WebApi控制器,该控制器通过EF6从SQL Server DB获取一组“人员”。很简单的例子

到目前为止,我已经尝试过的事情没有成功:-禁用代理生成-禁用延迟加载-添加Includes以获得带有linq和string参数的子引用。-用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)
        {
            ...
        }            
    }
Run Code Online (Sandbox Code Playgroud)

现在,在控制器的任何位置都不会引发异常。但是,异常显示在浏览器中:

"<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()
Run Code Online (Sandbox Code Playgroud)

该错误告诉我,在using子句弹出后,其他东西正在尝试读取上下文,但是我茫然地知道那可能是什么?如您所见,在返回之前,我将枚举数据从上下文复制到本地列表中。让我塞满了!

任何建议表示赞赏。

Pet*_*r B 5

线

persons = entities.Persons.Take(5);
Run Code Online (Sandbox Code Playgroud)

是有关如何检索数据的定义,但此时数据本身尚未被检索(“延迟执行”)。该行位于using(){}构造内部,因此在此之后立即进行DbContext处理。稍后,View需要数据,已查询DbContext,但已关闭。

解决方案:
在关闭DbContext之前检索所有数据。通常使用ToArray()或来完成此操作ToList(),以最适合您的方式。

因此,该行应为例如:

persons = entities.Persons.Take(5).ToArray();
Run Code Online (Sandbox Code Playgroud)