2012-07-20 55 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