【问题标题】:Correlated subquery in LinqLinq 中的相关子查询
【发布时间】:2012-11-16 23:50:04
【问题描述】:

我有一张员工表和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

【问题讨论】:

  • Linq to Objects for EF Ver 4.2
  • LINQ to objects 与 EF 无关。什么意思?
  • 我的错 - 使用 LINQ to Entities

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


【解决方案1】:

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

【讨论】:

  • 为什么要两次使用Join方法(EmployeeAddress和EmployeeCourseStatus)?
  • @mveith 避免嵌套 from 查询
  • 子查询中第二个连接末尾的“进入课程”正是我所需要的。
  • @SergeyBerezovskiy 我知道这是旧线程,但想知道你为什么在 linq 查询中使用 join,它在没有 join 的情况下在 sql 中解决。
【解决方案2】:

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

【讨论】:

  • 不是每个人都同意这是提高可读性 :-)
  • 这是一个口味问题,我实际上更喜欢相反的情况——除了连接子句之外的所有情况下的 lambdas :)
【解决方案3】:

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

如果不行,emp.name 和 adr.country 的类型是什么?

【讨论】:

  • emp.name 和 adr.country 都是字符串。错误是 - 无法创建类型为“System.Data.Objects.ObjectSet`1”的常量值。此上下文仅支持原始类型(“例如 Int32、String 和 Guid”)
猜你喜欢
  • 2013-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多