Need help in writing LINQ Query to get count of employee based on department.
Department Model
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
Employee Model
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 Query
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");
}
Output Expected
Department Count (or employees)
Human Resource 10
Information Tech 5
Question How to write a LINQ Query to get the output as above. Please guide me.
Department= y.First().Department.Name,(assumesDepartmentcontains a property namedName)Department= y.KeytoDepartment= y.First().Department.NameGroupBy(e => e.Department.Name)in which case you can useDepartment= y.Key,the "first" cannot be used a final query operation"