【发布时间】:2017-12-28 08:28:04
【问题描述】:
在编写 LINQ 查询以获取基于部门的员工数量时需要帮助。
部门模型
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
员工模型
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
MyViewModel
public class MyViewModel
{
public string Department { get; set; }
public int count { get; set; }
}
LINQ 查询
public ActionResult shows()
{
//one department can have many employees and one employee can only be parrt of one department
// below LINQ query fetches the count of employees belonging to each department
var x = _context.Employees.Include("Department").GroupBy(e => e.DepartmentId)
.Select(y=> new MyViewModel{
Department= y.Key, // ERROR HERE AS Cannot type cast string to integer
count = y.Count()
}).ToList();
// code removed for brevity
return Content("x");
}
预期输出
Department Count (or employees)
Human Resource 10
Information Tech 5
问题 如何编写 LINQ 查询以获取上述输出。请指导我。
【问题讨论】:
-
Department= y.First().Department.Name,(假设Department包含一个名为Name的属性) -
@StephenMuecke:我真的很抱歉,但我没能关注你。在本教程中,“youtube.com/…”在 1:57 分钟对导师来说工作正常。
-
将
Department= y.Key更改为Department= y.First().Department.Name -
该教程使用
GroupBy(e => e.Department.Name),在这种情况下您可以使用Department= y.Key, -
我收到了
the "first" cannot be used a final query operation"的错误
标签: c# asp.net asp.net-mvc linq asp.net-mvc-5