Linq to SQL:Group by和Sum from 3 table Join

时间:2014-11-28 09:14:09

标签: linq-to-sql

我有一个查询,如下所示,有关将其转换为LINQ的一些问题。

查询是:

SELECT P.ProjectID, MIN(ProjectName) As PrjName, SUM(Hours * Rate) As Price
FROM Projects P 
        INNER JOIN Tasks T ON P.ID = T.ProjectID
        INNER JOIN Timesheets Time ON T.TaskID = Time.TaskID
GROUP BY P.ProjectID

我对Linq的最佳尝试是(还没有完成工作): 问题出在?

 var q = from p in db.Projects
                join t in db.Tasks on p.ProjectID equals t.ProjectID
                join time in db.Timesheets on t.TaskID equals time.TaskID
                group p by p.ProjectID into g
                select new { ID = g.Key, Name = ??, Price = g .Sum(x => x??)};

    var q = (from p in db.Projects
            join t in db.Tasks on p.ProjectID equals t.ProjectID
            join time in db.Timesheets on t.TaskID equals time.TaskID into g
              select new {p.ProjectName, g.Sum(x => x.Hours * x.Rate)
              ); --get invalid anonymous type at Hours * Rate

1 个答案:

答案 0 :(得分:2)

试试这个:

from p in Projects
      join t in Tasks on p.Id equals t.ProjectID
      join ts in Timesheets on t.TaskID equals ts.TaskId
      group t by new { proj= p, timesheet = ts} into g
      select  new
        {
           g.Key.proj.Id,
           g.Key.proj.ProjectName,
           Price = g.Key.timesheet.Rate * g.Key.timesheet.Hours
        }