LINQ查询表达式中的子查询

时间:2014-12-15 13:05:32

标签: c# linq

以下是我的SQL查询:

select e.id, m.id, e.Name, (select 1 where e.Id Is Null) as NotExists
    from    Employee e 
            INNER JOIN Department d
            ON e.Id = d.Id  
            LEFT JOIN Manager m
            ON e.Id = m.Id
            order by e.Name

我正在尝试将上述查询写入LINQ,如下所示:

var result = from e in employeeRep
             join d in departmentRep
             on e.Id equals d.Id
             join m in manager
             on e.Id = m.Id
             order by e.Name
             select new
             {
               Name = e.Name,
               EmpId = e.Id,
               ManagerId = m.Id,
               DepartmentId = d.Id,
               DeparmentName = d.Name,
               NotExists = // here I want to write this query (select 1 where e.Id Is Null) as NotExists
             } ;

任何人都可以告诉我如何实现这个目标

由于

2 个答案:

答案 0 :(得分:0)

如果 Id nullable,那么您可以执行此操作:

select new
             {
               Name = e.Name,
               EmpId = e.Id,
               ManagerId = m.Id,
               DepartmentId = d.Id,
               DeparmentName = d.Name,
               NotExists = e.Id == null ? 1 : 0 

            }

答案 1 :(得分:0)

您可以使用let关键字。它允许您创建子查询,为其指定名称,然后在代码中使用它们。虽然,它在更复杂的子查询中更有用,但它也适用于此。

var result = from e in employeeRep
         join d in departmentRep
         on e.Id equals d.Id
         join m in manager
         on e.Id = m.Id
         order by e.Name
         let mySub = // write your query here.
         select new
         {
           Name = e.Name,
           EmpId = e.Id,
           ManagerId = m.Id,
           DepartmentId = d.Id,
           DeparmentName = d.Name,
           NotExists = mySub
         };