3
From r In ReceiptLines
Where 
r.RECEIPT.RECEIPTDATE >= _reportStartDate 
And r.RECEIPT.RECEIPTDATE <= _reportEndDate
Let amount = r.QUANTITY * r.PRICE
Let discount = r.RECEIPTDISCOUNTs.Sum(Function(d) d.DISCOUNT) 
where discount > 0
Group By Department = r.ITEMSTYLE.ITEM.CATEGORY.DEPARTMENT.DEPARTMENTNAME
Into Sales = Sum(amount - discount), 
Average = Average(amount - discount), 
Count = Count()

I am fetching all departments and their sales, average, count from the ReceiptLine, Receipt, ReceiptDiscount tables. The problem i am facing is, if i remove where discount > 0, I am getting null exception. But if I include that, then I only get sales that has discount. How would I write query that bring all sales less discount (if it has one). Any help is highly appreciated.

1
  • It looks like your code is VB.NET. I added that tag, if that is wrong you can correct that. Commented Nov 12, 2011 at 18:29

2 Answers 2

8

This is a common pitfall with LINQ2SQL.

The function SUM in SQL returns null if there are no items in the collection, but the signature of Enumerable.Sum() returns an int. This gives a runtime exception when the SQL query return null where the LINQ2SQL provider expects an integer.

The solution is to cast the result of the sum to a nullable integer and use GetValueOrDefault to convert the null-case to 0.

Replace

Let discount = r.RECEIPTDISCOUNTs.Sum(Function(d) d.DISCOUNT) 

with

Let discount = CType(r.RECEIPTDISCOUNTs.Sum(Function(d) d.DISCOUNT), Integer?).GetValueOrDefault(0)
Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried:

...
Let amount = r.QUANTITY * r.PRICE
Let nDiscount = r.RECEIPTDISCOUNTs.Sum(Function(d) d.DISCOUNT) 
Let discount = IIf(nDiscount == Nothing, 0, nDiscount)
Group By Department = r.ITEMSTYLE.ITEM.CATEGORY.DEPARTMENT.DEPARTMENTNAME
...

3 Comments

I think Muthu's code looks like VB.NET and the ternary operator is pronounced IF(Condition, TrueValue, FalseValue) in VB.NET.
Yep! got used to code in c# for a long time. Haven't noticed that. thanks.
and... null is spelled Nothing in VB.NET. Writing VB.NET when you are used to c# feels like you have poured two cups of coffee in you keyboard. You just type along as usual, but you get red squiggles everywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.