Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The cast to value type 'Int32' failed because the materialized value is null. [duplicate]

I have the following code insdie my asp.net mvc web application:-

SystemInformation s = new SystemInformation()
            {
AssetCount = new AssetCount() {

                CustomerCount = entities.AccountDefinitions == null ? 0 : entities.AccountDefinitions.Count(),
                RackCount = tms.TMSRacks == null ? 0 : tms.TMSRacks.Count(),
                ServerCount = tms.TMSServers == null ? 0 : tms.TMSServers.Count(),
                CustomCount = tms.CustomAssets==null? 0 : tms.CustomAssets.Sum(a => a.Quantity)

            },

But currently if any of the Enumerable are empty i will get the following error:-

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

like image 818
john Gu Avatar asked Jan 07 '14 16:01

john Gu


1 Answers

The problem is probably that the tms.CustomAssets collection is empty. To fix write something like the following:

var tmpCustomCount = tms.CustomAssets.Sum(a => (int?)a.Quantity);

...
AssetCount = new AssetCount() 
{
...
   CustomCount = tmpCustomCount ?? 0
}
like image 66
Magnus Avatar answered Oct 19 '22 10:10

Magnus