Linq:在访问属性之前检查空值

时间:2012-07-20 15:31:30

标签: c# .net linq

请就错误提出建议。 这是代码

   void Main()
   {
      var a = from id in TechnicalProducts
        where id.Id == "ID-4591"
        select new {
         Country = id.Computers.Select (x => new {x.Location.ParentLocation.ParentLocation.ParentLocation.ParentLocation.Code}),
        };
      Console.WriteLine(a);
   }

错误:导航属性“Code”返回的条目为null,无法初始化。您应该在访问此属性之前检查空值

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

somevar = x.Location.ParentLocation.ParentLocation.ParentLocation.ParentLocation.Code ?? 0

编辑:     您的代码可能如下所示:

var a = from id in TechnicalProducts
        where id.Id == "ID-4591"
        select new {
         Country = id.Computers.Select (
              x => new{
                x.Location.ParentLocation.ParentLocation.ParentLocation.ParentLocation.Code ?? 0
                      }
        )};

答案 1 :(得分:1)

您可以在查询中添加空检查:

WHERE x.Location.ParentLocation.ParentLocation.ParentLocation.ParentLocation.Code != null

否则请使用@Behnam建议的coalesce operator。该运算符只返回链中的第一个非空值。