简体   繁体   中英

How can I write this query in LINQ

I have this query

SELECT t.NomeTipo, sum(v.QtdProduto) 
FROM [dbo].[Vendas] AS V 
RIGHT JOIN [dbo].[Produtos] AS P ON V.IdProduto = P.IdProduto
INNER JOIN [dbo].[Tipos] AS T ON P.IdTipo = T.IdTipo  
group by t.NomeTipo 
order by t.NomeTipo

I have tried this

var queryTipos = from vendas in repositorioVendas.Vendas
join produtos in repositorioProduto.Produtos.DefaultIfEmpty()
on vendas.IdProduto equals produtos.IdProduto
join tipos in repositorioTipo.Tipos
on produtos.IdTipo equals tipos.IdTipo
group vendas by new { tipos.NomeTipo, vendas.QtdProduto }
into novoGrupo
select new
{
    NomeTipo = novoGrupo.Key.NomeTipo,
    QtdProduto = novoGrupo.Sum(x => x.QtdProduto)
};

With this query I got only two results, but when I run straight from the database I get something like this:

Bebidas     16
Bolos       14
Frios       16
Pães        21

The trick is to realize that you can rewrite your query with a left join instead of a right join by swapping the order of the first two tables and that Linq doesn't have a way to really handle right joins. Also you're grouping was wrong.

var queryTipos = from produtos in repositorioProduto.Produtos 
                 join vendas_pj in repositorioVendas.Vendas
                 on vendas_pj.IdProduto equals produtos.IdProduto into joined
                 from vendas in joined.DefaultIfEmpty()
                 join tipos in repositorioTipo.Tipos
                 on produtos.IdTipo equals tipos.IdTipo
                 group vendas by tipos.NomeTipo
                 into novoGrupo
                 select new
                 {
                    NomeTipo = novoGrupo.Key,
                    QtdProduto = novoGrupo.Sum(x => x.QtdProduto)
                 };

Basically a Left join in SQL

From TableA
Left Join TableB 
On TableA.ID = TableB.ID

is done in Linq like this

from a in repo.TableA
join b_pj in repo.TableB
on a.ID equals b_pj.ID into joined
from b in joined.DefaultIfEmpty()

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