Linq中的相关子查询

时间:2012-11-16 23:50:04

标签: c# entity-framework linq correlated-subquery

我有一张员工表和EmployeeCourseStatus表。

我想显示每位员工的名单,其中包含已完成课程的数量(status = "CMP")。

我有以下相关子查询,导致以下错误:

var query = (from emp in Employee
                     join adr in EmployeeAddress on emp.id = adr.EmployeeID
                     select new
                     {
                        id = emp.id,
                        name=emp.name,
                        country=adr.country,
                        CompletedCourseCount = (from c in employeeCourseStatus where c.empid = emp.id && c.status == "CMP" select c.id).count()
                     }

错误:

  

仅支持Premitive类型。

等效的SQL子查询将是 -

Select emp.id
       , emp.name
       , adr.Country
       , CompletedCourseCount = (select count(id) from EmployeeCourseStatus where id = emp.id and status = "CMP") 
from   Employee emp
       JOIN employeeaddress adr ON adr.EmployeeID = emp.ID

3 个答案:

答案 0 :(得分:3)

加入序列时使用equals关键字

var query = from emp in Employee
            join adr in EmployeeAddress on emp.id equals adr.EmployeeID
            join c in EmployeeCourseStatus on emp.id equals c.empid into courses
            select new
            {
               id = emp.id,
               name = emp.name,
               country = adr.country,
               CompletedCourseCount = courses.Where(x => x.status == "CMP").Count()
            };

答案 1 :(得分:1)

我更喜欢使用lambda表达式(为了便于阅读 - 特别是在Join方法中):

Employee.Join(EmployeeAddress, emp => emp.id, adr => adr.EmployeeID, (emp, adr) => new
{
    id = emp.id,
    name = emp.name,
    country = adr.country,
    CompletedCourseCount = employeeCourseStatus.Count(c => c.empid == emp.id && c.status == "CMP")
});

答案 2 :(得分:0)

请尝试使用计数查询中的where c.empid = emp.id替换where c.empid == emp.id

如果这不起作用,emp.nameadr.country的类型是什么?