views:

254

answers:

4

I am creating a method that collects accumulated totals throughout the month. The problem is that there may not be charges for some of the items in a given month so no rows would be returned.

I can see how this would error with no data:

double fuelCost = (double)(from a in db.EquipmentFuelLogs
                           where a.wdEquipmentMainGeneralOID == vehicleKey &&    
                                (monthBeginDate < a.Date1 && a.Date1 < monthEndDate)
                           select a.TotalCost).Sum();

What is the best approach to detect no fuel transactions for that month and set the fuel cost to 0? Just do a try catch? This article spoke of the problem but no solution.

+1  A: 
monthBeginDate >= a.Date1
Andrey
Well, that would be a bug as well, wouldn't it. But that isn't what I was asking.
Mike Wills
Not a bug as far as I can see...
leppie
A: 

Why would it error with no data?

It is zero then, that's how it works (well unless I am completely mistaken here).

leppie
The function returns null. There are no rows returned on some vehicles. A null causes a InvalidOperationException. Do I just catch that and set fuelCost to 0?
Mike Wills
Ah, because TotalCost is nullable I assume :) So do where a.TotalCost.HasValue, select a.TotalCost.Value.
leppie
Someone is confused here (probably me). The value returned is null because there are no rows to produce a value. If I wasn't doing a Sum(), the row count would be 0.
Mike Wills
A: 

I added a catch to catch the error. I never found a different solution.

Mike Wills
+2  A: 

The issue is because the where is returning no sequence therefor the sum cannot work, however if you use .DefaultIfEmpty before the sum it works fine.

decimal? orderValue = orders.Where(ee => ee.Name == "SomeName") .DefaultIfEmpty().Sum(s => s.OrderCost);

Hope this helps.

David
I'll try this next time I need to do this.
Mike Wills