简体   繁体   中英

transform sql to linq with join, group-by and where

I have the following sql, which I want to convert to 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

What I have now in linq is the following, but the group by doesn't work.

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;

Think this should work:

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)})

Try

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)
        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM