繁体   English   中英

是否存在Linq to Enties的子查询,就像在此T-SQL中一样

[英]Is there a not in sub-query for Linq to Enties as in this T-SQL

假设经典的自引用Employee表,其中每个员工最多可以有一个ReportsTo,如使用此T-SQL片段和样本数据创建的:

create table Employees
(
    Id          int identity primary key,
    Name        nvarchar(30),
    Region      nvarchar(10),
    ReportsTo   int null
        foreign key(ReportsTo) references Employees(Id)
)

insert into Employees values('Boss','HO',null)
insert into Employees values('Underling', 'HO',
        (select Id from Employees where Name='Boss'))
insert into Employees values('Self Important', 'Region 1',
        (select Id from Employees where Name='Underling'))
insert into Employees values('Very Underling', 'Region 1',
        (select Id from Employees where Name='Self Important'))

我可以使用此T-SQL为区域1选择管理器

select * from Employees 
where Region = 'Region 1' and 
ReportsTo not in (select Id from Employees where Region = 'Region 1')

换句话说,经理是一名在其所在地区没有报告的员工。

现在,如何使用Linq确定1区的管理器?

这样的事情怎么样:

from e in context.Employee
where e.Region == "Region 1" 
&& !(from e2 in context.Employee
     where e2.Region == "Region 1"
     select e2.Id).ToList().Contains(e.ReportsTo)
select e;

我相信你可以通过Linq在查询中查询。 它看起来像下面

db.Employees.Where(u => u.Region = 'Whatever').Where(u =>
    db.Employees
    .Where(v => ReportsTo <> 'Whatever')
    .Select(v => v.Id)
    .Contains(u.Id)
)

这可能需要一些工作才能准备好,但我认为这是一般的想法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM