Click here to Skip to main content
15,886,069 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have Two tables on is Employees and other is Employeeschedules. Id column of Employees have foreign key relation with EmployeeId column of Employeeschedules table.

Employees Model Class


public class Employee : ModelBase<employee>
{
public string Name { get; set; }

public bool IsDeleted { get; set; }
}

Employeeschedules Model Class


public class EmployeeSchedule : ModelBase<employeeschedule>
{

[ForeignKey("Employee"),Required]
public long EmployeeId { get; set; }
public virtual Employee Employee { get; set; }
public DateTime Date { get; set; }

[Required]
public DateTime FromHours { get; set; }

[Required]
public DateTime ToHours { get; set; }

[Required]
public bool SlotStatus { get; set; }

[Required]
public TimeSpan TotalHours { get; set; }
}


I want result Like this


EmployeeId Name TotalHours
1 Mohan 3:00:00
2 Sarvan 2:30:00
5 Yogesh 1:00:00
3 Abhishek 0:30:00

What I have tried:

var empsch = from e in Db.Employees
join es in Db.EmployeeSchedules
on e.Id equals es.EmployeeId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by e.Id into grouped
select new { EmployeeId=grouped.Key,Name= grouped.Select(t => t.Employee.Name), TotalHours=???
};
Posted
Updated 21-Apr-16 1:28am

1 solution

Something like this:

C#
from e in Db.Employees 
join es in Db.EmployeeSchedules 
on e.Id equals es.EmployeeId 
group es by {e.Id} into g
select new {EmployeeId = g.EmployeeId , TotalHours = g.Sum(e => e.TotalHours)}
 
Share this answer
 
v2
Comments
Raj_1984 21-Apr-16 8:38am    
its giving error "can not implicitly convert System.Timespan to long?"
Raj_1984 21-Apr-16 8:44am    
can anybody give this answer
John C Rayan 21-Apr-16 10:01am    
The error clearly says what the problem is. This is because TotalHours in Timespan and Sum is not happy with that. The solution I gave you is an example and you have to workout how you are going to calculate the total hours. Why is your total hours is Timespan. I would expect it as long.
Raj_1984 22-Apr-16 1:02am    
TotalHours may contain hour, minute & second so I had gone for that.Thats why I can not change datatype of that column.
John C Rayan 21-Apr-16 10:06am    
Try with Aggregate() function instead of Sum(). You have to get syntax by googling it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900