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

asp.net, asp.net-mvc-4, c#

Solution

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
}

Problem

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.

Original source

Related problems