簡體   English   中英

Linq中的相關子查詢

[英]Correlated subquery in 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()
                     }

錯誤:

僅支持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

在連接序列時使用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()
            };

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

請嘗試將where c.empid = emp.id替換為count計數查詢where c.empid == emp.id

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM