开发者

LINQ - accessing an Int column on Child table and handle the situation when there are no child rows

Here is a cut down version of my linq query;

 var list = from inv in db.Inventories
                       where 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 an inventory record does not have to have any rows in InventoryMedia, i have a开发者_如何学Cdded the .FirstOrDefault(), which then returns a null and linq is smart enough not to throw an ONSTIOO error, but i do get this 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

Now i understand that i could just change the anonymous type to a class and define this integer as a nullable type, but i dont want to do that. I have also tried using the if null command "?? 0", but that is not supported on reference types like int. I know i can use .DefaultIfEmpty() and set a default value for the anonymous type, but how can i set a default value for the integer or is there another alternative?


Try projecting to the desired properties first then use FirstOrDefault(). That way you won't have to deal with the possibility of a null reference exception and the type will be whatever is appropriate for the property. Cast to nullable if necessary.

var list = from inv in db.Inventories
           where 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(),
           };


cast to an nullable int

int? value;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜