简体   繁体   English

如何在 LINQ 中编写此查询

[英]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.诀窍是意识到您可以通过交换前两个表的顺序使用左连接而不是右连接重写查询,并且 Linq 没有真正处理右连接的方法。 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基本上是 SQL 中的左连接

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

is done in Linq like this在 Linq 中是这样完成的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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