如何在linq中使用此查询。 EmployeeID是另一个表。
select *
from Employees where EmployeeID
in (select ID from EmployeeIDs where ID between 3 and 7)
答案 0 :(得分:2)
var result= (
from e in db.Employees
where
(
from eId in db.EmployeeIDs
where eId.ID>=3 && eId.ID<=7
select eId.ID
).Contains(e.EmployeeID)
select e
);
其中db是linq数据上下文
或者您也可以这样做:
var result= db.Employees.Where(a=>a.EmployeeID>=3 && a.EmployeeID<=7);
或者您也可以这样做:
var result= (
from e in db.Employees
where
(
from eId in db.EmployeeIDs
where eId.ID>=3 && eId.ID<=7
&& e.EmployeeID==eId.ID
select eId.ID
).Any()
select e
);
答案 1 :(得分:1)
听起来像是想要加入:
var query = from emp in employees
join empId in employeeIds.Where(x => x.ID >= 3 && x.Id <= 7)
on emp.EmployeeID equals empID
select emp;
如果你真的需要两张桌子的话。另一方面,如果您可以假设任何employeeIds
employee.ID
中始终存在有效ID,那么您可以使用:
var query = employees.Where(x => x.EmployeeID >= 3 && x.EmployeeID <= 7);
答案 2 :(得分:0)
即使在SQL中,SELECT
语句中嵌套的IN
也是多余的。
你可以写
SELECT *
FROM Employees
WHERE EmployeeID Between 3 and 7
在SQL中Between 3 AND 7
只是Column >= 3 and Column <= 7
因此,您可以针对您的EF上下文编写以下内容。
var results = from e in context.Employees
where EmployeeId >= 3 && EmployeeId <= 7
select e;
答案 3 :(得分:0)
使用联接非常简短直接;
from emp in db.Employees
join eid in db.EmployeeIDs on emp.EmployeeID equals eid.ID
where emp.EmployeeID >= 3 && emp.EmployeeID <= 7
select emp
这也将导致非常理智且直接的SQL,而没有嵌套选择(为了便于阅读而编辑)
SELECT *
FROM Employees AS emp
INNER JOIN EmployeeIDs AS eid ON emp.EmployeeID = eid.ID
WHERE (emp.EmployeeID >= 3) AND (emp.EmployeeID <= 7)