LINQ从2个表中获取数据,1个与group by一起加入

时间:2018-06-07 08:18:51

标签: asp.net-mvc entity-framework linq linq-to-sql

我有2张桌子。

Department         |              Questions
ID     Name        |         DepartmentID   QTitle   QDescription
1       a          |             1           aaa          bbb
2       b          |             1           ddd          ccc      
3       c          |             2           eee          fff
                   |             2           ggg          hhh

| 我想用ViewModel分组数据并在View中显示。我可以使用QTitle获取分组数据,但不能使用QDescription。

Linq查询

var questions= (from s in dbContext.Questions
                         join b in dbContext.Department
                         on s.DepartmentID equals b.ID
                         group s.QTitle by b.DepartmentID into g
                         select new QuestionGroupedViewModel
                         {
                             DepartmentName= g.Key,
                             QTitle= g.ToList()
                         }).ToList();

视图模型

public class QuestionGroupedViewModel
    {
     public string DepartmentName{ get; set; }
     public List<string> QDescription{ get; set; }
     public List<string> QTitle{ get; set; }
    }

1 个答案:

答案 0 :(得分:2)

COUNT(*)