Simple Question?

Posts   
 
    
Posts: 33
Joined: 31-May-2005
# Posted on: 20-Feb-2006 05:42:47   

I'm using GetScalar to perform a simple SUM on a single decimal column (e.g. SELECT SUM(column1) FROM table WHERE column2 = 3).

Everything works fine except when there is no data to return. In these cases, the return value of GetScalar is null, so I can't cast to a Decimal. The only way I could work around this was to check the return value each time, which is a bit of a pain since we use GetScalars all over the place, and the code in the examples is so much cleaner. Is there an easy way to default the return value of GetScalar to 0 instead of null?

E.g. here was the code I wanted to use:

Decimal commPaid = (Decimal)adapter.GetScalar(CommissionPaidFields.CommissionAmountPaid, null, AggregateFunction.Sum, expression);

But here's what I ended up needing to write (since I sometimes received an InvalidCastException):


Decimal commPaid = 0;
object testCommPaid = adapter.GetScalar(CommissionPaidFields.CommissionAmountPaid, null, AggregateFunction.Sum, expression);
if (object != null)
{
  commPaid = (Decimal)testCommPaid;
}

Any thoughts? Thanks, Josh

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39930
Joined: 17-Aug-2003
# Posted on: 20-Feb-2006 08:27:52   

THe problem is that the value returned by getscalar can be of different types. This means that there can't be a GetScalar with 1 return type which internally checks if hte returned value is null, and a getscalar can be NULL so it 's a legitimate value to return, hence the object type.

Frans Bouma | Lead developer LLBLGen Pro
Posts: 65
Joined: 07-Dec-2005
# Posted on: 20-Feb-2006 13:15:33   

Rather than casting, use the Convert.ToDecimal() function.