Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

join, group by and sum in linq

I want to group overtime work hours of employees by employeeId and get data of employeeNames and total monthly overtime work hours of employees. But this linq query gives translation error.

var results = 
    from overtime in context.Overtimes
    join employeeCredential in context.EmployeeCredentials
        on overtime.EmployeeId equals employeeCredential.id
    join employeeDetail in context.EmployeeDetails
        on employeeCredential.id equals employeeDetail.employeeId
    where overtime.Month == month && overtime.Year == year
    group new { overtime, employeeCredential, employeeDetail } by overtime.EmployeeId into g
    select new MonthlyOvertimeWorkHours
    {
        EmployeeName = g.First().employeeDetail.employeeName,
        TotalWorkHourOfMonth = g.Sum(t => t.overtime.OvertimeWorkHour)
    };

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Until EF Core 6, you cannot access to records after grouping (which is usually bad). Only aggregates and Key is available.

To fix issue just add employeeName to grouping key.

var results = 
    from overtime in context.Overtimes
    join employeeCredential in context.EmployeeCredentials
        on overtime.EmployeeId equals employeeCredential.id
    join employeeDetail in context.EmployeeDetails
        on employeeCredential.id equals employeeDetail.employeeId
    where overtime.Month == month && overtime.Year == year
    group new { overtime, employeeCredential, employeeDetail } by new { overtime.EmployeeId, employeeDetail.employeeName } into g
    select new MonthlyOvertimeWorkHours
    {
        EmployeeName = g.Key.employeeName,
        TotalWorkHourOfMonth = g.Sum(t => t.overtime.OvertimeWorkHour)
    };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading