C# 使用linq检查if not exists子句
这是我一直试图解决的情况 让我们看一张员工桌C# 使用linq检查if not exists子句,c#,linq-to-sql,join,union,C#,Linq To Sql,Join,Union,这是我一直试图解决的情况 让我们看一张员工桌 Create Table Employee ( Employeeid int primary key, EMPname varchar(50), ManagerEmplId int reference key Employee (EmployeeID) TreeLevel int, .... ) 在这里,我需要找到所有叶级员工 叶级员工-所有有经理但没有任
Create Table Employee
(
Employeeid int primary key,
EMPname varchar(50),
ManagerEmplId int reference key Employee (EmployeeID)
TreeLevel int,
....
)
在这里,我需要找到所有叶级员工
叶级员工-所有有经理但没有任何人向其报告的员工。我得到了db的一点帮助,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.
无论树的深度如何,此查询都应该起作用:
var leafEmps =
(from emp in _db.Employees
where !_db.Employees.Any(e => e.ManagerEmplId == emp.EmployeeId)
select emp);
您可以尝试右外部联接,并确保左侧为空 在这篇文章中,你可以找到一个很好的例子,说明如何在linq中实现这一点
from b in _db.Employees
from c in _db.Employees.Where(o=> o.ManagerEmplId == b.Id).DefaultIfEmpty()
where c == null
要做到这一点,请找到所有经理,然后搜索那些不是经理的人
var leafemps = from emp in _db.Employees
let managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct()
where !managersids.contains(emp.Employeeid)
select emp
当根据建议更改代码时,我得到以下错误信息:在此上下文中仅支持基元类型(“如Int32、String和Guid”)。确定,糟糕的是,我无法帮助获得异常,因为下面无法比较'System.Collections.Generic.IEnumerable'1'类型的元素。只支持基本类型(如Int32、String和Guid)和实体类型。这是我的原始查询,我用泛型查询掩盖了我的问题,但这也是简单的返回(从b.BranchID上的join-firm中的b到b.BranchID等于从g.DefaultIfEmpty()中的sc到g的firm.ParentBranchID)当b.DeletedDate==null&&g==null选择b.ToList().ToDictionary(k=>k.BranchName,v=>v.BranchName);Getting Error无法比较“System.Collections.Generic.IEnumerable”“1”类型的元素。仅支持基元类型(如Int32、字符串和Guid)和实体类型。return(从
*中的b连接到b.BranchID上的_db.branchs等于从g.DefaultIfEmpty()中的sc连接到
*中)
*当b.DeletedDate==null&&g==null
*选择b.ToList()
*.ToDictionary(k=>k.BranchID,v=>v.BranchName)
*获取错误
*无法比较'System.Collections.Generic.IEnumerable'1'类型的元素。仅支持基本类型(如Int32、字符串和Guid)和实体类型。请将
g==null
替换为sc==null
。我如何格式化他们使用的注释
var leafemps = from emp in _db.Employees
let managersids = _db.Employees.Select(emp => emp.ManagerEmplId ).Distinct()
where !managersids.contains(emp.Employeeid)
select emp