Two Sums in the same table with clauses Where

0

I am new to using LINQ lambda expressions and I have to make a query in a table called stock and it has attributes id, prodId, prodCode, Quantity, status, ubicacion knowing that status can be available or not available, what I want to do is get one list with the total amount and the total available caity of each product, that is to say if I have for example the following stock:

Stock1: prodCode=A; Qty=1; Status=Disponible; Ubicacion=sd1
Stock2: prodCode=A; Qty=2; Status=NoDisponible; Ubicacion=sd2
Stock3: prodCode=B; Qty=2; Status=Disponible; Ubicacion=sd3
Stock4: prodCode=B; Qty=2; Status=Disponible; Ubicacion=sd4

The result should be:

prodCode=A;  TotalQuantity=3;  QtyDisponible=1
prodCode=A; TotalQuantity=4; QtyDisponible=4

Someone can help me please I have been punching code for 3 days and doing tests and it does not come out.

This is the code I did:

Context.Stocks.Where(e=>e.IsActive /*&& ( e.ProductCode=="63149")*/)
.GroupBy(s=>s.ProductCode)
.SelectMany(gr=>gr.Select(st=>new
{
             TotalQuantity = gr.Sum(c=>c.Quantity),

             Count = gr.Count(),
             Pr= st.ProductCode,
             PrId = st.ProductId,
             StockInternalStatus = st.StockInternalStatus   
}))
//.Distinct()
.GroupJoin
(Context.Stocks.Where(p=>p.StockInternalStatus=="Disponible" && p.IsActive)
, ss => ss.PrId, sss => sss.ProductId, 
(ss,sss) => new { TotalQuantity = ss.TotalQuantity, ProductCode = ss.Pr,
QtyDisponible = sss.Sum(a=>a.Quantity)
})
.Distinct()
.DefaultIfEmpty()

And if I specify a product code if it gives me the result for that product but I decompose to get the result of all the products I get the following error error:

  

Error: The cast to value type 'System.Decimal' failed because the   materialized value is null. Either the result type's generic parameter   or the query must use a nullable type.

According to my understanding of this error is that there are products from the first query that when the GroupJoin is made with the second does not come out because they are not available, as I only take out those that are available in the second one, what interests me to get the total available but I'm not sure I understand it well.

Thanks in advance for your help.

    
asked by yassine errakba 27.09.2018 в 20:45
source

0 answers