Mediator
Mediator

Reputation: 15378

Casting a value to Decimal

Here is my code:

var finiGames = myRepos.Games
                       .Where(x => x.StatusGameId == (int)StatusGameEnum.Finish 
                              && x.EndDateTime > DateTime.Today)
                       .DefaultIfEmpty();
//error line
decimal? sum = finiGames.Sum(x => x.WinCost);

The error I am getting:

Error converting cast a value type "Decimal", because materializuemoe value is null. The overall result of the type parameter or a request to use a type that allows the value null.

What is the proper way to get a decimal??

Upvotes: 0

Views: 317

Answers (3)

Damith
Damith

Reputation: 63065

decimal sum = ((decimal?)finiGames.Sum(x => x.WinCost)) ?? 0;

Upvotes: 0

Matt
Matt

Reputation: 26971

Try adding a ToList() to finiGames. It might kill your performance, but EF probably can't handle the conversion in the data (SQL) layer.

Upvotes: 0

Magnus
Magnus

Reputation: 46909

You need to cast the WinCost to a nullable decimal inside the Sum

decimal? sum = finiGames.Sum(x => (decimal?)x.WinCost);

Upvotes: 4

Related Questions