简体   繁体   中英

How to group by with left join by multiple columns using linq and get count of grouped records?

Lets say we have: Employee class (prop: EmployeeID, EmployeeName, DepartmentID, Department - as navigation prop) and Department class (prop: DepartmentID, DepartmentName, Employees - as navigation prop). The relationship between this two tables is one to many. Now the concrete example:

Employee table

EmployeeID EmployeeName DepartmentID     
1          Peter        1               
2          Anna         1                
3          John         2   
          

Department table

DepartmentID  DepartmentName                                                        
1             IT                                                                    
2             Marketing                                                              
3             HR         

                                                   

The final result should be showing every department (DepartmentID, DepartmentName, NumOfEmployees) regardless does it have an employees with number of employees in the department, for example: 1, IT, 2 | 2, Marketing, 1 | 3, HR, 0.

My syntax was:

var dbContext.Departments.Include(d => d.Employees).    
                          GroupBy(d => new { d.DepartmentID, d.DepartmentName }).
                          Select(x => new {
                                   DepartmentID = x.Key.DepartmentID,
                                   DepartmentName = x.Key.DepartmentName,
                                   NumOfEmployees = x.Count()
    }).ToList();

The problem is that attribute NumOfEmployees is assigned with 1 for every department, and don't know why. How would correct lambda expression LINQ syntax look like?

I would say that you don't need GroupBy here and can do as simple as:

var result = dbContext.Departments
    .Select(x => new 
    {
        DepartmentID = x.DepartmentID,
        DepartmentName = x.DepartmentName,
        NumOfEmployees = x.Employees.Count()
    })
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM