2

I have the following query:

int? Giver = Convert.ToInt32(db.vwAssignments.Sum(a => a.Amount));

but if there is no records that matches the search criteria then the following error will be raised

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

pls help

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
shailendra
  • 205
  • 1
  • 8
  • 21

1 Answers1

2

The basics of defensive programming:

  • first assign the result of your Sum() operation to a nullable variable

    object resultOfSum = db.vwAssignments.Sum(a => a.Amount);
    
  • check for NULL! and only if it's not null, then convert it to an INT

    if(resultOfSum != null)
    {
       int Giver = Convert.ToInt32(resultOfSum);   
    }
    

Also: if your Amount field is a Int to start with, most likely this will already give you NULL or a valid Int - I think that call to Convert.ToInt32() is not necessary:

int? Giver = db.vwAssignments.Sum(a => a.Amount);

if(Giver.HasValue)
{
   ......
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459