Skip to main content
 首页 » 编程设计

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

2024年02月13日21xing901022

我有一个 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();