1

This method throws exception when db.Profits doesn't have any records. How to prevent explode page

public double getProfitSum()
{
   return db.Profits.Where(p => p.IdUser.UserId == WebSecurity.CurrentUserId).Sum(p => p.Value);
}

Error :

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Krasimir
  • 259
  • 4
  • 9
  • 28

3 Answers3

2

try that:

    var result = db.Profits.Where(p => p.IdUser.UserId == WebSecurity.CurrentUserId).Sum(p => p.Value);

    if(result != null)
      {
          return result;
      }
    return 0;
Moondustt
  • 864
  • 1
  • 11
  • 30
1

The reason must be Sum() expects not nullable value. But your result might give null.

try

return db.Profits.Where(p => p.IdUser.UserId == WebSecurity.CurrentUserId
   && p.Value != null).Select(x=>(double?)x.Value).Sum() ?? 0.0M;
Novice
  • 2,447
  • 3
  • 27
  • 33
  • This has various hidden features of c# http://stackoverflow.com/questions/9033/hidden-features-of-c – Novice Mar 15 '13 at 17:16
0

or even better

    public double getProfitSum()
                {
        var result = db.Profits.Where(p => p.IdUser.UserId == WebSecurity.CurrentUserId
               && p.Value != null).Sum(p => p.Value);

 return result == null ? 0 : result;
        }
NoWar
  • 36,338
  • 80
  • 323
  • 498
  • not working if (result != null) -The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?' – Krasimir Mar 15 '13 at 16:56
  • The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type. Same – Krasimir Mar 15 '13 at 17:01