transform sql with subquery into query on entity

0

I'm needing and am having trouble getting this sql with subquery and doing the same thing in c # entity.

SELECT  Id,Nome,
      (SELECT Count(Id) FROM Pedidos
      WHERE Pedidos.ColaboradorId = Colaborador.Id) AS NumeroPedidos
  FROM Colaborador
  ORDER BY Nome DESC;

I need to turn this SQL up.

var retornoColaborador = db.Colaboradores.Where(a => a.Id == db.Pedidos.Where(b => b.ColaboradorId == a.Id).Count());

I tried to do something like this but it did not work.

    
asked by anonymous 18.06.2018 / 14:27

2 answers

1

You do not need a subquery to solve this problem, a LEFT JOIN combined with a SUM() can help you, see:

SELECT
    Colaborador.Id,
    Colaborador.Nome,
    SUM( CASE WHEN Pedidos.Id IS NULL THEN 0 ELSE 1 END) AS NumeroPedidos
FROM
    Colaborador
LEFT JOIN
    Pedidos ON ( Pedidos.ColaboradorId = Colaborador.Id )
GROUP BY
    Colaborador.Id,
    Colaborador.Nome
ORDER BY
    Colaborador.Nome DESC;
    
18.06.2018 / 15:02
0

Try as follows, by giving include , already done sub query

var retornoColaborador = db.Colaboradores.Include(p=> p.Pedidos).Select(p => new
    {
        p.ColaboradorId,
        p.Nome,
        p.Pedidos.Count
    });
    
18.06.2018 / 14:48