在一个Linq查询中从多个表中取回数据

时间:2019-02-18 02:50:55

标签: asp.net linq

我有3张桌子:

  1. 课程-此存储有关培训的信息
  2. xref_session_faculty-此交叉引用了培训和老师
  3. 用户-所有老师的名单

在一个(或多个)LINQ查询中,我想获取所有课程,并为每节课程进行培训的老师。每个会话在数据库中可以有零个或更多的老师。

sessions = db.sessions
.Where(x => x.seminar_id == seminarId)
.ToList()
.Select((x, i) => new fees
{
    id = x.id,
    sessionTitle = x.title,

    teacherNames = "By:" + String.Join(",",
            x.xref_session_faculty.ToList()
            .Select(q => db.users
                .Where(m => m.id == q.user_id)
                .Select(t => t.firstName).ToList()
            )
    )
})
.ToList();

使用此教师名可以打印出By:System.Collections.Generic.List 1 [System.String],System.Collections.Generic.List 1[System.String]

什么是正确的查询格式?

2 个答案:

答案 0 :(得分:1)

 teacherNames = "By:" + String.Join(",",
        x.xref_session_faculty.ToList()
        .Select(q => db.users
            .Where(m => m.id == q.user_id)
            .Select(t => t.firstName).FirstOrDefault()
        )
)

您需要将ToList更改为FirstOrDefault函数以获得正确的结果

答案 1 :(得分:0)

private var sessions = (from session in db.sessions.Where(x => x.seminar_id == seminarId) select new { id = session.id, sessionTitle = session.title, teacherNames = (from faculty in db.xref_session_faculty. where (x => x.session_id == session.id) join us in db.uses on faculty.user_id equals us.user_id select new { us.firstName, other_field_names }) });