I am building a little application in .NET 4 MVC 2 for the office foosball table. I have this repository with a method summing all the values of one column (decimal) using LINQ to SQL. It looks like this:
public decimal GetPlayerRating(int id)
{
var playerRating = (from r in db.Ratings
where r.PlayerID == id
select r.Points).Sum();
return playerRating;
}
The problem is that sometimes when it’s called it returns null because the given player does not have any records in the table. That’s fine — in that case it should just return zero. But I get this error:
The null value cannot be assigned to a
member with type System.Decimal which
is a non-nullable value type.Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.Exception Details:
System.InvalidOperationException: The
null value cannot be assigned to a
member with type System.Decimal which
is a non-nullable value type.
How can I tell my method that it is okay to return a null value? Thanks!
Try the null coalese operator
That will never return a null.
If you really need to return a nullable valuetype, though try this
Adding a ? to the end of a value type like double is rewritten into Nullable < type > (Nullable < double > here)
When dealing with a nullable value type, be sure to check if it has a value (not null)