从SQL转换为Linq

时间:2013-04-19 07:04:28

标签: sql linq

我对整个Linq故事都很陌生,但我对SQL有很好的理解。

我需要重建从SQL到Linq的查询。我的SQL查询工作正常,到目前为止,我已经尝试用Linq自己做一些事情,但没有取得好成绩......

是否有人可以帮助我将此查询从SQL转换为Linq?
我真的准备好在这整个故事中学到新东西。如果你能解释为什么它在linq中那样工作会很好。

SQL语句

SELECT TimeReport.EntryDate
     , SUM(TimeReport.Hours) AS Hours
     , SUM(BillingRate.HourlyRate * TimeReport.Hours) AS Amount
FROM BillingRate 
    INNER JOIN Activity 
        ON BillingRate.BillingRateId = Activity.BillingRateIt 
        INNER JOIN TimeReport 
            ON Activity.ActivityId = TimeReport.ActivityId 
                RIGHT OUTER JOIN Dossier 
                    ON TimeReport.DossierId = Dossier.DossierId
                    INNER JOIN LBU 
                        ON Dossier.LBUId = LBU.LBUId 
                    INNER JOIN BU 
                        ON Dossier.BUId = BU.BUId 

GROUP BY TimeReport.EntryDate
HAVING SUM(TimeReport.Hours) > 0
ORDER BY TimeReport.EntryDate desc

我对Linq感到厌倦

var x = (from br in ctx.BillingRate
                    join a in ctx.Activity on br.BillingRateId equals a.BillingRateIt
                    join tr in ctx.TimeReport on a.ActivityId equals tr.ActivityId

                    select br)
                  .GroupJoin(
                     (from d in ctx.Dossier
                       join l in ctx.LBU on d.LBUId equals l.LBUId
                       join b in ctx.BU on d.DossierId equals

感谢您的帮助和快速回答。

我尽一切努力!!

1 个答案:

答案 0 :(得分:2)

拥有导航属性时不需要联接。由于我不确切知道您的模型是什么样的,因此请使用以下内容作为起点并根据您自己的规格进行调整:

// starting with Dossier handles the right outer join condition
var timeRecordQuery = 
        from d in ctx.Dossier
        from tr in d.TimeReports
        // this handles the inner join conditions after the right outer join
        where d.LBUId.HasValue && d.BUId.HasValue
        // project what you want to use
        select new 
        {
            EntryDate = tr.EntryDate,
            Hours = tr.Hours,
            // simply use navigation properties, no need to join
            Amount = tr.Activity.BillingRate.HourlyRate * tr.Hours 
        };

var resultsQuery = from e in timeRecordQuery
                   // group by EntryDate
                   group e by e.EntryDate into g
                   // get sum of hours for each EntryDate value
                   let hours = g.Sum( x => x.Hours ) 
                   // having clause
                   where hours > 0
                   // project results
                   select new 
                   {
                       EntryDate = g.Key,
                       Hours = hours,
                       Amount = g.Sum( x => x.Amount ) 
                   };