Entity Framework 查询返回的结果少于预期

Entity Framework query returning less results than expected

我有一个 Entity Framework 查询,我正在计算一些学生的成绩。查询如下:

(
    from s  in Students.Where(a => a.GroupId == groupId)
    from q  in Quizzes.Where(a => a.GroupId == groupId)
    from qa in QuizAnswers.Where(a => a.UserId == s.UserId && a.QuizId == q.QuizId).DefaultIfEmpty()
    select new Response
    {
        UserId       = s.UserId,
        UserFullName = s.FullName,

        ActivityType = "Quiz",
        ActivityId   = q.QuizId,
        ActivityName = q.Name,
        DueDate      = q.DueDate,
        Score        = qa == null ? null : qa.Score,
        MaxScore     = qa != null ? qa.MaxScore ?? 0 : 0,
        IsSent       = qa != null && qa.DateSent != null,
    }
)
.OrderBy(a => a.DueDate).ThenBy(a => a.ActivityId)
.AsEnumerable()
.GroupBy(a => new User
{
    a.UserId,
    a.UserFullName,
})

此查询加入所有学生和所有测验。我没有直接查询 QuizAnswers,因为如果学生没有打开测验,它还不存在,但我需要一个占位符来显示在成绩单上。

现在,当我在 LinqPad 上 运行 查询时,查询工作正常。在我正在处理的示例中,它显示了 4 个测验和 700 个学生,并且所有条目都被正确检索。

但是,在应用程序(它是一个 ASP.NET MVC 4 应用程序)上放置相同的查询,在迭代查询时,它会显示所有 700 名学生,但只显示第一个测验。我也试过添加和删除测验,但它总是只显示第一个。

自从 LinqPad 运行 查询正确后,Entity Framework 或 ASP.NET MVC 有什么不同之处吗?也许是优化,或者配置什么的?

在 VS GroupBy 应该是 Type

稍微更改查询的顺序。

改用这个:

  from tt in ( from s in Folder.Where(a => a.GroupId == groupId)
   from q in Quizzes.Where(a => a.GroupId == groupId)
   from qa in QuizAnswers.Where(a => a.UserId == s.UserId && a.QuizId == q.QuizId).DefaultIfEmpty()
   )
    group tt by new {a.UserId, a.UserFullName}
     into grp
   select new
   {
       UserId = grp.tt.UserId,
       UserFullName = grp.tt.FullName,

       ActivityType = "Quiz",
       ActivityId = grp.tt.QuizId,
       ActivityName = grp.tt.Name,
       DueDate = grp.tt.DueDate,
       Score = grp.tt == null ? null : grp.tt.Score,
       MaxScore = grp.tt != null ? grp.tt.MaxScore ?? 0 : 0,
       IsSent = grp.tt != null && grp.tt.DateSent != null,
   }
   )

   .OrderBy(a => a.DueDate).ThenBy(a => a.ActivityId)
   .AsEnumerable()

问题是我在 LinqPad 和 Visual Studio 中都不是 运行 完全相同的查询。

在 LinqPad 中,我有 GroupBy(a => new { /* stuff */ }),而在 Visual Studio 中,我有 GroupBy(a => new User { /* stuff */ }),其中 User 是 class 而不是 [=24 的一部分=].

正如我后来发现的那样,GroupBy 需要一个具有覆盖相等性的 class,匿名 class 有,但我的自定义 class 没有。

解决方法是在User的定义中覆盖Equals