将SQL语句转换为Linq

时间:2015-12-03 10:10:59

标签: entity-framework linq

这是我的示例查询

Select id from employee where id in
(select employeeid from employeecenter where CenterCodeId in 
(select CenterCodeId from employeecenter where employeeid=40))

我们如何使用Linq

实现上述目标
//Gets all the centerCodeIds allotted to an employee
Session["LoggedUserId"] = 40;
List<int> _centerCodeIds = _cmn.GetCenterEmpwise(Convert.ToInt32(Session["LoggedUserId"]))
                           .Select(x => x.Id).ToList();

//Get all employees having the above centercodids
List<int> _employeeIds = _db.EmployeeCenters
                        .Where(x => _centerCodeIds.Any(cc => x.Id == cc))
                        .Select(x => x.Employee.Id).ToList();

1 个答案:

答案 0 :(得分:1)

这是:

List<int> _employeeIds = _db.EmployeeCenters.Where(x => _db.EmployeeCenters
                        .Where(y => y.EmployeeId == 40)
                        .Select(y => y.CenterCodeId)
                        .Contains(x.CenterCodeId))
                      .Select(x => x.EmployeeId)
                      .ToList();

但您确定在查询中需要第二个子选择吗?