Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq中的相关子查询_C#_Entity Framework_Linq_Correlated Subquery - Fatal编程技术网

C# Linq中的相关子查询

C# Linq中的相关子查询,c#,entity-framework,linq,correlated-subquery,C#,Entity Framework,Linq,Correlated Subquery,我有一个employee表和EmployeeCourseStatus表 我想显示每个员工的列表以及完成的课程计数(status=“CMP”) 我有以下相关子查询,导致以下错误: var query = (from emp in Employee join adr in EmployeeAddress on emp.id = adr.EmployeeID select new

我有一个employee表和
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

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


如果不起作用,加入序列时使用
equals
关键字时,
emp.name
adr.country
的类型是什么

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方法中):


不是每个人都会同意这是可读性的提高:-)这是一个品味问题,实际上我更喜欢相反的情况-lambdas在所有情况下,除了join子句:)为什么要使用join方法两次(EmployeeAddress和EmployeeCourseStatus)?@mveith以避免嵌套
from
在第二次联接结束时查询“into courses”,在子查询中,这正是我所需要的。@SergeyBerezovskiy我知道这是一个旧线程,但我想知道为什么在linq查询中使用join,而在sql中不使用join进行求解。emp.name和adr.country都是字符串。错误为-无法创建“System.Data.Objects.ObjectSet`1”类型的常量值。EF版本4.2LINQ to Objects的此contextLinq to Objects中仅支持基元类型(“如Int32、字符串和Guid”)。INQ to Objects与EF无关。你什么意思?我的坏习惯-使用LINQ访问实体
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")
});