[Fixed] The cast to value type ‘System.Decimal’ failed because the materialized value is null.

Updated on     Kisan Patel

Full Error:

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

This type of error occurred when you should work with singleton collection in linq query.

For Example,

int records = db.Records
              .Sum(x => x.Number);

In above query, it will raise the following type of error if Records table has no rows.

The cast to value type ‘System.Int32’ failed because the materialized value is null. Either the result type’s generic parameter or the query must use a nullable type.

Solution:

The possible solution for this type error is to use Enumerable.DefaultIfEmpty<TSource> Method.

For Example,

int records = db.Records
              .Select(c => c.Number)
              .DefaultIfEmpty(0)
              .Sum();

As shown in above example, Firstly you need to select any type of values (Int32, Decimal, Double etc) from the objects which met the condition and then use .DefaultIfEmpty() method before the .Sum() method.

Here is another examples that demonstrate how to use DefaultIfEmpty<TSource>(IEnumerable<TSource>) to provide a default value in case the source sequence is empty.

List<int> numbers = new List<int>();

foreach (int number in numbers.DefaultIfEmpty())
{
    Console.WriteLine(number);
}
/*
This code produces the following output: 
0
*/

Source:
http://stackoverflow.com/questions/28265473/how-do-i-check-my-lambda-expression-for-null
https://msdn.microsoft.com/en-us/library/vstudio/bb360179(v=vs.100).aspx


Entity Framework

Leave a Reply