实体命令执行异常

时间:2015-03-02 23:03:56

标签: asp.net-mvc entity-framework-6

编译时我得到实体命令执行异常。相同的代码行在其他地方工作正常,但我需要它返回此异常。

//Working fine here!
Questionnaire questionnaireeeee = context.Set<Questionnaire>().Include(q => q.QuestionnaireQuestions.Single(q => q.ID == 1);
//need to see who is logged in, administrator or professor
 string userId = User.Identity.GetUserId();
//...
if(User.IsInRole("Administrator"))
{
    //grouping subject instances by same semester
    var subjectInstancesBySemester = from subjectInstances in context.SubjectInstances group subjectInstances by subjectInstances.Semester;
    foreach (var subjectInstancesGroup in subjectInstancesBySemester)
    {
         // getting questionnaire related to this semester
         if(subjectInstancesGroup.Key.QuestionnaireID != null)
         {
        //Exception is here!
             Questionnaire questionnaire = context.Set<Questionnaire>().Include(q => q.QuestionnaireQuestions).Single(q => q.ID == (int) subjectInstancesGroup.Key.QuestionnaireID);
             //...
         }
    }
}

我用断点检查,subjectInstancesGroup.Key.QuestionnaireID的值为1,表格中有一行问卷,ID为1.问题出在哪里?

1 个答案:

答案 0 :(得分:2)

实体框架可能无法编译您给予他的表达式树。

添加.ToArray()是否可以解决问题?

var subjectInstancesBySemester = 
       from subjectInstances in context.SubjectInstances 
       group subjectInstances by subjectInstances.Semester;

foreach (var subjectInstancesGroup in subjectInstancesBySemester.ToArray())
{
     // getting questionnaire related to this semester
     if(subjectInstancesGroup.Key.QuestionnaireID != null)
     {
         var questionnaireId = (int) subjectInstancesGroup.Key.QuestionnaireID;
         Questionnaire questionnaire = context.Set<Questionnaire>().Include(q => 
                  q.QuestionnaireQuestions).Single(q => q.ID == questionnaireId);
         //...
     }
}

通过添加.ToArray(),可以对数据库执行查询。实体框架现在不需要在更复杂的查询中编译它。无论如何,对于完整的返回集,我不会认为这将是一个问题。