使用JOIN,GROUP BY和SUM将SQL映射到Entity Framework查询

时间:2017-09-27 10:46:55

标签: entity-framework linq group-by linq-to-entities

我想将以下SQL映射到EF查询。我发现了一些类似的主题,但仍未能实现映射。 {0} ... {2}是SQL参数。

SELECT TaskGroup.Project AS Project
SUM(Datediff(minute, WorkLog.StartTime, WorkLog.EndTime)) / 60 AS Hours
FROM WorkLog INNER JOIN TaskDefinition ON WorkLog.TaskDefinitionID = TaskDefinition.ID
INNER JOIN TaskGroup ON TaskDefinition.TaskGroupID = TaskGroup.ID
WHERE WorkLog.EmployeeID = {0} AND WorkLog.Status = 5 AND
   WorkLog.StartTime >= {1} AND WorkLog.EndTime < {2}
GROUP BY TaskGroup.Project

1 个答案:

答案 0 :(得分:0)

这个怎么样?

var query = (from wl in WorkLog
            join td in TaskDefinition on wl.TaskDefinitionID equals td.ID
            join tg in TaskGroup on td.TaskGroupID equals tg.ID
            where wl.EmployeeID == { 0} && wl.Status == 5 
                && wl.StartTime >= { 1} && wl.EndTime < { 2}
            select new
            {
                Project = tg.Project,
                StartTime = wl.StartTime,
                EndTime = wl.EndTime
            })
            .GroupBy(o => o.Project)
            .Select(g => new
            {
                Project = g.Key,
                Hours = g.Sum(o => (o.EndTime - o.StartTime).Minutes) / 60
            });