多对多关系表和Linq查询加入它们

时间:2017-05-08 13:17:05

标签: c# entity-framework linq

我有给定的情景表,在部门和房间之间有多对多的关系。还有一个交叉点。 enter image description here

我有以下名为DepartmentWithRoom的课程

    date  id   variable
    2000   1    100
    2000   2    101
    2001   1    50
    2001   2    48

问题:我想使用Linq创建一个DepartmentWithRoom对象列表,其中包含相关RoomId的列表。

我尝试但无法创建连接。请提前帮助谢谢

1 个答案:

答案 0 :(得分:0)

以下内容应解决问题: -

 var result = from department in Departments
                     join junction in Junctions on department.DepartmentId equals junction.DepartmentId into rooms
                     select
                         new DepartmentWithRoom
                             {
                                 DepartmentId = department.DepartmentId,
                                 DepartmentName = department.DepartmentName,
                                 RoomIdList = rooms.Select(r => r.RoomId).ToList()
                             };