我有一个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(),因此可以直接往返数据库。当我到达底部的结果时,它没有进行任何数据库调用。我只是将这些值编组到视图模型中。

最佳答案

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

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

07-28 02:28
查看更多