2012-07-20 64 views
0

请咨询之前检查空值。 这是代码的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); 
    } 

错误:由导航属性“代码”返回一个项为无效,不能初始化。你应该检查空值,访问此属性之前

回答

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

但如果将我加入这行? – Swapnil 2012-07-20 17:22:03

+0

请检查我的帖子。 – 2012-07-21 04:37:39

1

你可以添加在您的查询中输入一个空格:

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

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

+0

我在哪里添加这个? – Swapnil 2012-07-20 17:21:51

+0

在您的WHERE语句 – 2012-07-20 17:22:21

+0

所以语句看起来像这样的附加条件。对?其中id.Id == “ID-14591” && x.Location.ParentLocation.ParentLocation.ParentLocation.ParentLocation.Code!= NULL但后来它给出了一个新的错误。 “名称'x'在当前上下文中不存在” – Swapnil 2012-07-20 17:29:44