[英]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.name
和adr.country
的類型是什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.