Reputation: 259
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.
Upvotes: 1
Views: 57
Reputation: 2487
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;
Upvotes: 1
Reputation: 37632
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;
}
Upvotes: 0
Reputation: 884
try that:
var result = db.Profits.Where(p => p.IdUser.UserId == WebSecurity.CurrentUserId).Sum(p => p.Value);
if(result != null)
{
return result;
}
return 0;
Upvotes: 2