将SQL转换为LINQ to Entities WHERE IN子句

时间:2013-05-15 01:45:46

标签: sql sql-server linq linq-to-entities

如何将此sql statetment转换为LINQ to Entities?

SQL语句:

Select * from Departments where DepartmentID  in (Select DepartmentID from Employees where FirstName like '%FirstName%' or LastName like '%LastName%')

我只有WHERE =(等于),我不能做WHERE IN子句

LINQ to Entities:

from t in db.Departments
where
  t.DepartmentID == -->Should be IN not EQUALS
    ((from t0 in db.Employees
    where
      t0.FirstName.Contains("FirstName") ||
      t0.LastName.Contains("LastName")
    select new {
      t0.DepartmentID
    }).FirstOrDefault().DepartmentID)
select t

2 个答案:

答案 0 :(得分:0)

(from d in db.Departments
 join e in db.Employees
     on d.DepartmentID equals e.DepartmentID
 where e.FirstName.Contains("FirstName") ||
       e.LastName.Contains("LastName")
 select t).Distinct()

答案 1 :(得分:0)

你可以用这个

var x = 
    (from t0 in db.Employees
    where
      t0.FirstName.Contains("FirstName") ||
      t0.LastName.Contains("LastName")
    select new {
      t0.DepartmentID
    }).FirstOrDefault().DepartmentID;

from t in db.Departments
where
  t.DepartmentID.contains(x.DepartmentID)
select t