0

I have three tables and they are linked like

grandparent -> parent -> child 

categoryType - > Categories - > Menus

when I try to run following

return categoryTypes.Select(x =>
                     new CategoryTypeIndexModel
                     {
                         Id = x.Id,
                         Name = x.Name,
                         Categories = x.Categories.Count,
                         Items = x.Categories.Sum(m => m.Menus.Count())
                     });

I get

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
youngseagul
  • 347
  • 5
  • 16
  • `x.Categories.Sum(m => (int?) m.Menus.Count())` – Habib Apr 01 '15 at 15:39
  • 1
    Items = x.Categories.Where(m => m.Menus != null && m.Any()).Any() ? x.Categories.Where(m => m.Menus != null && m.Any()).Sum(m => m.Menus.Count()) : 0 – IdahoSixString Apr 01 '15 at 15:49
  • Possible duplicate of [The cast to value type 'Int32' failed because the materialized value is null](http://stackoverflow.com/questions/6864311/the-cast-to-value-type-int32-failed-because-the-materialized-value-is-null) – Michael Freidgeim Sep 01 '16 at 05:37

1 Answers1

1

You are trying to count something that isn't there when Categories is null. I believe what Habib recommend would technically work but you would still have to account for a null value after the fact. I think the better solution would be to account for it in your linq directly by looking for null and providing a default

return categoryTypes.Select(x => new CategoryTypeIndexModel
    {
        Id = x.Id,
        Name = x.Name,
        Categories = (x.Categories == null) ? 0 : x.Categories.Count,
        Items = (x.Categories == null) ? 0 : x.Categories.Sum(m => m.Menus.Count())
    });

If Menus could ever be null you would also need to account for that in a similar fashion

TheRk
  • 341
  • 2
  • 8
  • When I tried Habib’s solution, it says Cannot convert lambda expression to type 'string' because it is not a delegate and when I tried yours it gave following error after running Cannot compare elements of type 'System.Collections.Generic.ICollection`1[[Repository.edmx.Category, Repository, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported. – youngseagul Apr 01 '15 at 16:07
  • I see checking for null like i mentioned wont work in EF unless you enumerate the collection first but that gets more complicated with lazy loading etc. In this case Habib's solution is the correct one but the error you get leads me to think CategoryTypeIndexModel.Categories is a string type? If so change that to a nullable int – TheRk Apr 01 '15 at 16:19
  • Categories is a table, not a field ….i converted coming result to IEnumerable first and then manipulated andit worked…thanks for help – youngseagul Apr 01 '15 at 16:25