Linq查询从一个表中的多个相同ID行中提取详细信息

时间:2017-10-20 05:21:49

标签: sql linq

我正试图通过这种格式的链接查询来提取数据。

ID | Name    | PHD    | MPhill   |  MS/Msc
++++++++++++++++++++++++++++++++++++++++++
1  | abc     | Botany | Botany   | -
2  | xyz     | Zoology| -        | Zoology

我的员工表是:

ID | Name  
+++++++++++
 1 | abc
 2 | xyz

EmpAcademic Infor表是:

ID | Emp_ref_id | Program_ref_id | Subject
+++++++++++++++++++++++++++++++++++++++++++
 1 |  1         |  1             | Botony
 2 |  1         |  2             | Botony
 3 |  2         |  1             | Zoology
 4 |  2         |  3             | Zoology

表程序如下:

ID | Name
+++++++++++
 1 | PhD
 2 | MPhill
 3 | MS/MSc

这是我的Linq查询

var result = (from p in Context.tblEmployees
                          join o in Context.tblEmpOfficialInfoes on p.ID equals o.Emp_ref_id
                          join a in Context.tblEmpAcademicQualifs on p.ID equals a.Emp_ref_id
                          join pro in Context.tblPrograms on a.Program_ref_id equals pro.ID
                          where pro.ID == 4
                          select new
                          {
                              p.LName,
                              pro.Name,
                              a.Subject
                          });

但它只提取那些已经完成博士学位的员工的详细信息。我如何在博士学位上提取Mphill,MS / MSc科目。和null的度值。

1 个答案:

答案 0 :(得分:0)

试试这个解决方案:

var result = (from ea in Context.EmpAcademics
              join emp in Context.Employees
              on ea.Emp_ref_id equals emp.ID
              join prog in Context.Programs
              on ea.Program_ref_id equals prog.ID
              group new {prog, ea} by new {emp.ID, emp.Name} into gr
              select new {
                  gr.Key.ID,
                  gr.Key.Name,
                  PHD = gr.Where(x => x.prog.Name == "PHD")
                          .Select(x => x.ea.Subject).FirstOrDefault(),
                  MPhill = gr.Where(x => x.prog.Name == "MPhill")
                             .Select(x => x.ea.Subject).FirstOrDefault(),
                  MS_Msc = gr.Where(x => x.prog.Name == "MS/Msc")
                             .Select(x => x.ea.Subject).FirstOrDefault()
              }).ToList();