0

我对整个 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

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

我感谢每一个努力!

4

1 回答 1

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 ) 
                   };
于 2013-04-19T08:19:45.577 回答