我正在使用 MVC3 并且仍在学习 LINQ。我在尝试将查询转换为 LINQ to Entities 时遇到了一些麻烦。我想返回一个员工对象。
SELECT E.EmployeeID, E.FirstName, E.LastName, MAX(EO.EmployeeOperationDate) AS "Last Operation"
FROM Employees E
INNER JOIN EmployeeStatus ES ON E.EmployeeID = ES.EmployeeID
INNER JOIN EmployeeOperations EO ON ES.EmployeeStatusID = EO.EmployeeStatusID
INNER JOIN Teams T ON T.TeamID = ES.TeamID
WHERE T.TeamName = 'MyTeam'
GROUP BY E.EmployeeID, E.FirstName, E.LastName
ORDER BY E.FirstName, E.LastName
我有几张表,但我只需要根据 EmployeeOperationDate 获取最新状态。这似乎在 SQL 中运行良好。我也在使用 Ninject 并将我的查询设置为返回 Ienumerable。我玩了按选项分组,但它随后返回 IGroupable。任何有关转换和返回属性对象类型的指导将不胜感激。
编辑:我开始在 LINQ 中写出来,但我不确定如何正确返回正确的类型或强制转换它。
public IQueryable<Employee> GetEmployeesByTeam(int teamID)
{
var q = from E in context.Employees
join ES in context.EmployeeStatuses on E.EmployeeID equals ES.EmployeeID
join EO in context.EmployeeOperations on ES.EmployeeStatusID equals EO.EmployeeStatusID
join T in context.Teams on ES.TeamID equals T.TeamID
where T.TeamName == "MyTeam"
group E by E.EmployeeID into G
select G;
return q;
}
编辑2:
这似乎对我有用
public IQueryable<Employee> GetEmployeesByTeam(int teamID)
{
var q = from E in context.Employees
join ES in context.EmployeeStatuses on E.EmployeeID equals ES.EmployeeID
join EO in context.EmployeeOperations.OrderByDescending(eo => eo.EmployeeOperationDate) on ES.EmployeeStatusID equals EO.EmployeeStatusID
join T in context.Teams on ES.TeamID equals T.TeamID
where T.TeamID == teamID
group E by E.EmployeeID into G
select G.FirstOrDefault();
return q;
}