Linq to Sql - use sum in where clause

I am trying to select orders that have more or less 2000 products ordered in them, depending on other values. I need to fetch information from the Orders table, but check that value in the OrdersProducts table, specifically the amount of OrdersProducts.ProductQty. I also need to do this using the predicate builder, due to other requirements. So far I have it, but it is not returning the results correctly. Its using nested lambda expressions, which I didn't know what I could do, but I tried it and it works but doesn't return the correct results.

Dim getOrders = From d In db.Orders _
                Where d.Status = OrderStatus.Approved _
                Select d

' Then a for loop adding parameters via Predicatebuilder... 


If over2000 = True Then
    ' over 2000
    predicate1 = predicate1.And(Function(d) (d.OrderProducts.Sum(Function(c) c.ProductQty > 2000)))

Else
    ' under 2000
    predicate1 = predicate1.And(Function(d) (d.OrderProducts.Sum(Function(c) c.ProductQty < 2000)))

End If

basePredicate = basePredicate.Or(predicate1)


' End For loop

getOrders = getOrders.Where(basePredicate)

      

I've removed some code for brevity, but I think it makes sense. How can i do this?? Thanks!

0


a source to share


1 answer


Try to change this:

(d.OrderProducts.Sum(Function(c) c.ProductQty > 2000))

      

:



(d.OrderProducts.Sum(Function(c) c.ProductQty) > 2000)

      

I haven't built this to test it, but it looks like it is currently trying to sum the results of a boolean comparison instead of summing the values ​​and then comparing.

+4


a source







All Articles