Entity Framework 出现 "此 ObjectContext 实例已释放,不可再用于需要连接的操作"
2012-07-24 17:29 smat 阅读(1810) 评论(1) 编辑 收藏 举报错误的写法:
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(); return list; } }
解决方案:(.ToList<Answer>())
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; } }
第二种就是查询的时候包含另一张表:
解决方案:(.Include("Answer"))
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; } } }