c# - null issue during usage of count and sum LINQ -


i have 3 tables , linked

grandparent -> parent -> child   categorytype - > categories - > menus 

when try 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

the cast value type 'system.int32' failed because materialized value null. either result type's generic parameter or query must use nullable type.

you trying count isn't there when categories null. believe habib recommend technically work still have account null value after fact. think better solution account in linq directly looking null , providing 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 ever null need account in similar fashion


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -