将T-SQL转换为LINQ Lambda

时间:2013-09-12 12:18:45

标签: c# sql-server linq tsql lambda

如果需要,我如何用LINQ lambda表达式或查询语法编写此查询?我已经尝试了一段时间了。多个连接使得它变得困难。联接的总记录超过2000,最终结果应该是大约15条记录

select 
    year([date]), 
    month([date]),
    sum(ot.rate)
from s as s 
join cs cs on cs.s_id= s.id
join ot ot on ot.id = cs.o_id
group by
    year([date]), 
    month([date])

这是我最接近但不会编译的。我无法从select块中访问ot属性。

    var query = from se in table_se
        join cs in table_cs on se.Id equals cs.S_Id
        join ot in table_ot on cs.O_Id equals ot.Id
        group se by new { se.Date.Year, se.Date.Month } into grp 
        select new
        {
            grp.Key.Year,
            grp.Key.Month,
            grp.Sum(ot.Rate)
        };

1 个答案:

答案 0 :(得分:5)

你非常接近 - Enumerable.Sum采用谓词

var query = from se in table_se
        join cs in table_cs on se.Id equals cs.S_Id
        join ot in table_ot on cs.O_Id equals ot.Id
        group ot by new { se.Date.Year, se.Date.Month } into grp 
        select new
        {
            Year = grp.Key.Year,
            Month = grp.Key.Month,
            Sum = grp.Sum(x => x.Rate)
        };