只要我不使用註釋掉的using
語句,以下代碼就可以工作。當我使用using
我得到The operation cannot be completed because the DbContext has been disposed
使用聲明和實體框架
public IQueryable<DTOs.FormQuestionDTO> GetForm(int id, int page = 0)
{
// FS stores pages starting with 1
page = page == 0 ? 1 : page;
//using (var db = new Models.FormEntities())
//{
var db = new Models.FormEntities();
var questions = from fq in db.FormQuestions
join q in db.Questions on fq.QuestionId equals q.QuestionId
where (fq.FormId == id) && (fq.PageNumber == page) && fq.Disabled == false
orderby fq.DisplayOrder
select new { q.QuestionId, q.QuestionText, fq.DisplayOrder, fq.PageNumber };
var dto = questions.Project().To<DTOs.FormQuestionDTO>();
if (questions == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
else
{
return dto;
}
//}
}
我最初的直覺是,在使用LINQ查詢後立即處置的DbContext
的,但把.Dipose()
一個finally
塊的內部時,我得到了同樣的錯誤。
這是怎麼回事?我沒有在C#中工作過一段時間,所以我可能錯過了一些簡單的東西。
什麼是堆棧跟蹤? – SLaks