我有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]
。
什么是正确的查询格式?
答案 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
})
});