此 ObjectContext 實例已釋放

參考文章:


http://www.cnblogs.com/dabaopku/archive/2011/07/16/2108351.html

http://www.cnblogs.com/lizhao/archive/2012/07/24/2606888.html

http://msdn.microsoft.com/zh-cn/data/jj713564.aspx


Entity 在 MVC 行爲上返回爲 json 對象時要對實體進行屬性導航。但是該Entity所在的Context已經在Controller中通過 using 釋放掉;但是Entity又具有Deferred Query Evaluation性質,因此,導航屬性對象沒有被加載,從而出現上述錯誤。


解決方法一

關掉延遲加載LazyLoadingEnabled=false;


解決方法二 .ToList<T>()

public static List<Answer> GetAnswer_ByQuestionID(int questionID)
{
   using (IA2SContext context = new IA2SContext())
     {
          var list = (from o in context.Answer
              where o.QuestionID == questionID
              select o).ToList<Answer>();
          return list;
     }

}


解決方法三

​在查詢中聲明包含導航屬性

public static List<Question> GetQuestionList_ByCategoryID(int categoryID)
{
      using (IA2SContext context = new IA2SContext())
      {
           var list = (from o in context.Question.Include("Answer")
               where o.CategoryID == categoryID && o.IsActive == true
               select o).OrderBy(p => p.SortOrder).ToList<Question>();
           return list;
          }
     }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章