【问题标题】:I can't wrap my ADO.NET Entity Model instance in a using statement here?我不能在这里将我的 ADO.NET 实体模型实例包装在 using 语句中吗?
【发布时间】:2013-08-08 20:20:18
【问题描述】:

我有一个 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 处理程序。通过开发者工具查看实际响应后,我发现根本原因如下:

操作无法完成,因为 DbContext 已被释放。

我是否以错误的方式使用此对象?我认为一切都很好,因为我正在调用 AsEnumerable() 进行初始查询,因此可以直接往返数据库。当我得到底部的结果时,它没有进行任何数据库调用。我只是将这些值编组到视图模型。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 编辑清除;发布后我意识到我的错误:)。
    【解决方案2】:

    快速解决方法是致电ToList()

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

    这将缩短延迟加载并防止错误发生。

    但是,IoC 容器可以通过非常适合 Web 的工作单元模式来简化这个问题。当一个 HTTP 动词触发时,你的上下文就会活跃起来,当会话结束时,IoC 会处理控制器的处置。无需using 或处理这些令人头疼的错误。

    【讨论】:

    • 你能不能顺便给我举个例子?我相信你说的是从 IoC 容器中获取上下文,然后配置 IoC 容器来处理它?我以前没有为此目的利用 IoC。
    • 我没有任何特定 IoC 框架的示例。有这个:blog.damianbrady.com.au/2012/03/07/…
    猜你喜欢
    • 2014-10-27
    • 2011-04-12
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多