0

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

   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);
   }

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

4

2 回答 2

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
                      }
        )};
于 2012-07-20T15:34:42.687 回答
1

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

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

否则,按照@Behnam 的建议使用合并运算符。该运算符仅返回链中的第一个非空值。

于 2012-07-20T15:40:48.660 回答