以下是我一直试图解决的问题
让我们拿一份员工表
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.
答案 0 :(得分:1)
无论树深度如何,此查询都应该可以解决问题:
var leafEmps =
(from emp in _db.Employees
where !_db.Employees.Any(e => e.ManagerEmplId == emp.EmployeeId)
select emp);
答案 1 :(得分:1)
您可以尝试右外连接,并确保左侧是空的。
在这篇文章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
答案 2 :(得分:0)
var managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct();
var leafemps = _db.Employees.where(emp => !managersids.contains(emp.Employeeid));
要做到这一点,请获取所有经理,然后搜索不是经理的人
var leafemps = from emp in _db.Employees
let managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct()
where !managersids.contains(emp.Employeeid)
select emp