【问题标题】:LINQ Get Data from 2 tables in 1 join with group byLINQ 从 2 个表中获取数据 1 加入 group by
【发布时间】:2018-06-07 08:18:51
【问题描述】:

我有 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; }
    }

【问题讨论】:

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


    【解决方案1】:
    var questions= (from s in dbContext.Questions
                             join b in dbContext.Department
                             on s.DepartmentID equals b.ID
                             group s by b.DepartmentName into g
                             select new QuestionGroupedViewModel
                             {
                                 DepartmentName= g.Key,
                                 QTitle= g.Select(x => x.QTitle).ToList(),
                                 QDescription = g.Select(x => x.QDescription).ToList()
                             }).ToList();
    

    【讨论】:

    • 我收到错误 Select 子句。无法将类型字符串隐式转换为 system.Collections.Generic.List。我在选择后添加了 .ToList() 。感谢您的帮助。
    • @Developer007 - 您还将面临错误 `DepartmentName= g.Key,` 作为对 ID 元素进行分组的原因
    • 是的,我试过了,我更改了 b.DepartmentName 而不是 b.DeparmentID
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多