Linq 中的相关子查询



我有一个员工表和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()
                     }

错误:

仅支持顶级类型。

等效的 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

连接序列时使用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()
            };

请尝试在计数查询中将where c.empid = emp.id替换为where c.empid == emp.id

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

我更喜欢使用 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")
});

相关内容

  • 没有找到相关文章

最新更新