Reputation: 2519
I am trying to make a simple record management app. I want to get the total employee count per department. I have this so far.
return Context.Employees
.GroupBy(e => e.DepartmentID)
.Select(x => new { Employee = x.Count() });
But it gives me a red wiggly line which says that I may be missing a cast.
Cannot implicitly convert type System.Linq.IQueryable<AnonymousType#> to System.Collections.Generic.IEnumerable<SimpleRMA.Models.Department>. An explicit conversion exists (are you missing a cast?)
Here is my desired result:
DepartmentName | Employees
Department1 | 4
Department2 | 6
How should I do it in lambda expressions? Thanks
Department Class:
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public string Location{ get; set; }
public virtual List<Employee> Employees { get; set; }
}
Employee Class:
public class Employee
{
public int EmployeeID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public DateTime Birthday { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
}
Upvotes: 2
Views: 2496
Reputation: 8902
You are return anonymous type which is not supported if you aren't using dynamic keyword as return value. Implement model class like this one and return it.
public class DepartmentEmployeesModel
{
public string DepartmentName { get; set; }
public string Employees { get; set; }
}
return Context
.Employees
.GroupBy(e => e.DepartmentID)
.Select(x => new DepartmentEmployeesModel { DepartmentName = x.Key, Employees = x.Count() }).ToList();
And change your method signature to
IEnumerable<DepartmentEmployeesModel> YourMethodName()
Upvotes: 1
Reputation: 2361
I would suggest getting the Departments instead.
It looks like you are using EntityFramework here. Why don't you just do return Context.Departments.Include("Employees")
. This would give you Collection of Department Objects with Employees filled in. You can get the count of employees in each department by doing departmentObject.Employees.Count().
Upvotes: 1