c# - LINQ - accessing an Int column on Child table and handle the situation when there are no child rows -
here cut down version of linq query;
var list = inv in db.inventories inv.inventorycode.startswith("005") select new { inv.inventorycode, inv.inventorymedias.where(im => im.mediatype == 0).firstordefault().synopsis, inv.inventorymedias.where(im => im.mediatype == 0).firstordefault().inventoryid };
...because inventory record not have have rows in inventorymedia, have added .firstordefault(), returns null , linq smart enough not throw onstioo error, error.
the cast value type 'int32' failed because materialized value null. either result type's generic parameter or query must use nullable type
now understand change anonymous type class , define integer nullable type, dont want that. have tried using if null command "?? 0", not supported on reference types int. know can use .defaultifempty() , set default value anonymous type, how can set default value integer or there alternative?
try projecting desired properties first use firstordefault()
. way won't have deal possibility of null reference exception , type whatever appropriate property. cast nullable if necessary.
var list = inv in db.inventories inv.inventorycode.startswith("005") select new { inv.inventorycode, synopsis = inv.inventorymedias .where(im => im.mediatype == 0) .select(im => im.synopsis) .firstordefault(), inventoryid = inv.inventorymedias .where(im => im.mediatype == 0) .select(im => im.inventoryid) .firstordefault(), };
Comments
Post a Comment