使用join,group-by和where将sql转换为linq

时间:2013-01-02 19:59:37

标签: c# linq join group-by aggregate

我有以下sql,我想将其转换为linq

SELECT Contrato.finca, SUM(Pago.Importe_subtotal)
FROM Pago, Contrato
WHERE Pago.Contrato = Contrato.ID AND Pago.pagado = 1
GROUP BY Contrato.finca
ORDER BY 2 DESC
GO

我现在在linq中有以下内容,但是group by不起作用。

var x = from contrato in ctx.Contratos 
        join pago in ctx.Pagos
        on contrato.ID equals pago.Contrato 
        where pago.pagado == true 
        group contrato by contrato.finca
        select contrato.Finca1;

2 个答案:

答案 0 :(得分:3)

认为这应该有效:

ctx.Pagos.Where(m=>m.pagado==true).GroupBy(m=>m.Contrato.finca) 
    .Select(m=> new { Id= m.Key, Val= m.Sum(n => n.Importe_subtotal)})

答案 1 :(得分:2)

尝试

var x = from contrato in ctx.Contratos 
        join pago in ctx.Pagos
        on contrato.ID equals pago.Contrato 
        where pago.pagado == true 
        group new {contrato, pago} by contrato.finca into g
        select new {
            key = g.Key, 
            sum = g.Sum(p => p.pago.Importe_subtotal)
        };