c# – 使用linq检查if not exists子句

这是我一直试图解决的情况

让我们拿一张员工表

Create Table Employee
(
        Employeeid int primary key,
        EMPname varchar(50),
        ManagerEmplId int reference key Employee (EmployeeID)
         TreeLevel int,
              ....
)

在这里,我需要找到所有叶级员工.

叶级员工 – 所有拥有经理但没有任何人向他们报告的员工.我有一个db的小帮助,它有TreeLevel专栏,我可以在3级指定选择任何人,但是我需要一个UNIONclause,这将使我在treelevel 2的所有员工都没有任何员工报告.
如果有助于创建linq查询,我只有3级树.

   return ((from b in _db.Employees
                && b.TreeLevel==3 && b.DeletedDate== null
                    select b)
                    .Union
                    (from b in _db.Employees

                     select b)

                    )
                    .ToDictionary(k => k.EmployeeID, v => v.EMPname);

更新:
真正的查询:

(from fi in firm 
 join bra in _db.Branches on fi.BranchID equals bra.ParentBranchID into g 
 from sc in g.DefaultIfEmpty() 
 where fi.DeletedDate == null && g == null 
 select fi)
 .ToList()
 .ToDictionary(k => k.BranchID, v => v.BranchName);

错误:

Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1'. 
Only primitive types (such as Int32, String, and Guid) and entity types are supported.

最佳答案 您可以尝试右外连接并确保左侧是空的.

在这篇文章How to do a full outer join in Linq?中,你可以找到一个如何在linq中做到这一点的好例子.

from b in _db.Employees
from c in _db.Employees.Where(o=> o.ManagerEmplId == b.Id).DefaultIfEmpty()
where c == null
点赞