as you gave more details about your database schema or your entity mapping, so it is difficult to deliver something more optimized.
Then try the following query.:
var entradas =
from entrada in db.entradas
group entrada.quant by entrada.idProduto into grupo
select new { idProduto = grupo.Key, quant = grupo.Sum() };
var saidas =
from saida in db.saidas
group saida.quant by saida.idProduto into grupo
select new { idProduto = grupo.Key, quant = grupo.Sum() };
var estoque =
from produto in db.produtos
join entrada in entradas in produto.idProduto equals entrada.idProduto into leftEntradas
from entrada in leftEntradas.DefaultIfEmpty()
join saida in saidas in produto.idProduto equals saida.idProduto into leftSaidas
from saida in leftSaidas.DefaultIfEmpty()
select new estoqueAtual {
produto = produto.idProduto,
saldo = (entrada?.quant ?? 0) + (saida?.quant ?? 0)
};
Could you improve your question? entering the information of which language you are working on and the products you have in the output class are the same as in the input class?
– Tiago S
Okay, I’ve edited the question
– Italo Rodrigo
I think the best way would be to leave the variable
saldo
product inside and do not see, at first, the need for a class tosaída
andentrada
. You can create them as methods within product and thus they would update the variable ofsaldo
.– Leonardo Pessoa
Is LINQ in memory, LINQ to SQL or LINQ to Entities? Uses Entity Framework?
– Leonel Sanches da Silva
@Gypsy omorrisonmendez use Entity Framework
– Italo Rodrigo
@leonardopessoa this database will be replicated, so I am preferring only to insert information than edit, to facilitate the time to replicate to other databases
– Italo Rodrigo
More questions: you will trigger this manual calculation or it will be reactive, for example, made as this one is a Trigger, but within C#? The "tables" are mapped as Models? If yes, you can update the code with the Models?
– Leonel Sanches da Silva
@Ciganomorrisonmendez I don’t know if I understand well: as soon as I open the form, I will do the calculation and list in a grid. The tables are mapped yes. As for changing them, I don’t know if I can do it, because I’m still learning.
– Italo Rodrigo
Ok, is your application Windows Forms or Web Forms? The calculation takes place in the grid or the inclusion/modification of information?
– Leonel Sanches da Silva