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
  • 704,970
  • 168
  • 1,303
  • 1,425
Krasimir
  • 259
  • 3
  • 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
  • 846
  • 1
  • 11
  • 29
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,389
  • 3
  • 25
  • 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
  • 34,755
  • 78
  • 302
  • 475
  • 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