5

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.

John John
  • 1
  • 72
  • 238
  • 501
  • It's because int32 is a primitive type not an object and thus not nullable. Try what is suggested in this [topic](http://stackoverflow.com/questions/2152717/what-is-the-integer-reference-type-in-c). TL;DR : when declaring RackCount (for example) using either the syntax `int32? RackCount;` or `Nullable RackCount;` – Irwene Jan 07 '14 at 16:52
  • 1
    You shouldn't have any of those collections be null in the first place. There shouldn't be any need for those checks. Keep in mind *null* and *empty* are two very different things for a collection. – Servy Jan 07 '14 at 16:56
  • @Grant yes i'm a little tired i've seen that after posting. I dont' know the comportment of the Sum method. Could it come from an error returning null ? – Irwene Jan 07 '14 at 16:59
  • 1
    @Sidewinder94 You'll get this error when trying to get the sum of an empty collection; you need to ensure that its' non-empty before summing the values. – Servy Jan 07 '14 at 17:05
  • so the problem is with the sum ? – John John Jan 07 '14 at 17:21

1 Answers1

8

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
}
Magnus
  • 45,362
  • 8
  • 80
  • 118
  • i can not reference the word "let".. – John John Jan 07 '14 at 17:22
  • 1
    @johnG right, you actually do not have a query, just put it in a varible before the expression. – Magnus Jan 07 '14 at 17:25
  • thanks a lot for the help. so i can conclude that .count() will work on an empty list while Sum() will not ? – John John Jan 07 '14 at 17:28
  • 1
    @johnG `Sum()` returns the same type as the column being summarized but when translated to SQL an empty query returns `null`, and `null` cant be mapped to `int`. I would call this a bug in the provider. (Linq-to-Object on an empty collection returns 0 for example) – Magnus Jan 07 '14 at 17:38