2012-02-08 90 views
3

與LINQ查詢工作我收到錯誤LINQ的,如何檢查是否字段的值爲null

System.NullReferenceException同時:未設置爲對象的實例 對象引用。

var db = from d in DepartmentBLL.GetDepartmentList() 
    join b in BudgetMasterBLL.GetBudgetMasterList()    
    on d.Departmentid equals b.Departmentid into leftJoin      
    from results in leftJoin.DefaultIfEmpty() 
    select new 
    { 
     Name = d.Name, 
     Create = results.Budgetmasterid == null ? "null": "value", //ERROR HERE 
     CreateURL = "frmBudgetInitial.aspx?departmentid=" + d.Departmentid.ToString() + "&departmentcategoryid=" + d.Departmentcategoryid.ToString() 
    }; 

我發現論壇上一些幫助,但並沒有解決我的問題,請指教。謝謝,

+0

首次檢查結果使用results.Budgetmasterid – DotNetUser 2012-02-08 13:30:50

+0

由於results.Budgetmasterid是之前爲null字符串值,你不應該檢查String.Empty而不是null? – 2012-02-08 13:37:15

回答

3

嘗試

Create = results == null || string.IsNullOrEmpty(results.Budgetmasterid) ? "null": "value", 

Create = results == null || string.IsNullOrWhitespace(results.Budgetmasterid) ? "null": "value", 
+0

這似乎是正確的,但與此同時,這不能解決第一個例外。 – 2012-02-08 13:45:11

+0

同意。點(。)仍然可以引用空對象。 – 2012-02-08 13:49:33

+0

@Ales我在你的評論[編輯]弗拉季斯拉夫後編輯。現在呢? – Bastardo 2012-02-08 14:07:45

2

這應該有助於

Create = results == null || results.Budgetmasterid == null ? "null": "value", //ERROR HERE 
+0

如果沒有結果返回,這不會將'true'賦值給'Create'嗎? – 2012-02-08 13:37:15

+0

沒有結果返回時,原始條件成立。我只是保持這一點。 – 2012-02-08 13:41:41

+0

順便說一句,「結果」甚至可能爲空?我的意思是,空集合!= null? – 2012-02-08 13:45:22