c# - 我不能在此处将我的 ADO.NET 实体模型实例包装在 using 语句中吗?

标签 c# .net asp.net-mvc asp.net-web-api ado.net-entity-data-model

我有一个 ASP.NET MVC WebAPI 项目,我有一个入口点可以通过 ID 进行调查。

public IEnumerable<Models.SurveyQuestionViewModel> GetSurveyById(int id)
{
    using (ITSurveyEntities model = new ITSurveyEntities())
    {
        var questions = model.SurveyQuestions.Where(s => s.SurveyId == id).AsEnumerable();
        if (!questions.Any())
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        return (from q in questions
                select new Models.SurveyQuestionViewModel
                {
                    Id = q.Id,
                    Question = q.Question,
                    LongDescription = q.LongDescription,
                });
    }
}

但是,当我向它发出请求时:

$.getJSON(apiUrl + '/' + id)
    .done(function (item) {
        surveyBusy.hide();
        var o = $('#survey-content');
    })
    .fail(function (jqXHR, textStatus, err) {
        var o = $('.error-bar');

        if (err === 'Not Found') {
            o.text('The survey you requested doesn\'t yet have any questions configured.');
        }
        else {
            o.text('An error occurred: ' + err);
        }

        o.fadeIn();
    });

我陷入了 :fail 处理程序。通过开发人员工具检查实际响应后,我发现根本原因如下:

The operation cannot be completed because the DbContext has been disposed.

我是不是用错了这个对象?我认为一切都很好,因为我正在为初始查询调用 AsEnumerable(),从而直接在前面进行数据库往返。当我到达底部的结果时,它没有进行任何数据库调用。我只是将这些值编码到 View 模型。

最佳答案

您正在延迟查询。试试这个:

return (from q in questions
                select new Models.SurveyQuestionViewModel
                {
                    Id = q.Id,
                    Question = q.Question,
                    LongDescription = q.LongDescription,
                }).ToList();

关于c# - 我不能在此处将我的 ADO.NET 实体模型实例包装在 using 语句中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18135382/

相关文章:

.net - 使用 MSBuild 脚本运行 MSTest 单元测试

javascript - 如何缩小和合并注释掉的 css 文件

c# - MVC 5 Web API - 使用 API key

c# - 部分 View 的复选框状态未返回到 Controller

c# - 如何从数组创建字典

c# - WPF - FrameworkElement - 枚举所有后代?

当类与命名空间共享名称时出现 C# 错误

c# - 删除第 N 级嵌套集合中的项目

.net - 有没有办法在 Windows (.NET) 中拦截进程 "Kill"命令?

javascript - 格式 "data"和 "name"highchart mvc asp.net