2014-01-15 65 views
0

我想檢查下面的代碼,如果沒有找到匹配,它不應該拋出對象引用null錯誤。有沒有辦法可以檢查AddRange()方法linq語句中的空對象?

itm.lstCustomziation.AddRange(
    (from xx in db.vw_DressingCustomization 
     where xx.CatID == itm.HeaderName.Value && xx.ProductID == itm.ProductID 
     select new itmCustomization() 
     { 
      catId = (int)xx.CatID, 
      custType = customizationType.Dressing, 
      isCustomziationDisplay = xx.IsDefaultDisplay, 
      isFixLimit = (bool)xx.isDefaultLimit, 
      maxLimit = (short)xx.DefaultFreeCount, 
      itmName = xx.Description, 
      isItemDefault = xx.IsDefaultDisplay, 
      price = (double)xx.MainPrice, 
      proId = (int)xx.ProductID 
     }).ToList<itmCustomization>()); 
+0

其實'ToList()'不應該返回null。如果序列爲空,則返回空列表。 –

+0

from xx in db.vw_DressingCustomization where xx.CatID == itm.HeaderName.Value && xx.ProductID == itm.ProductID here it failure .. – NoviceToDotNet

+0

Linq是SQL還是Entity Framework? –

回答

0

你應該把它分成多個步驟。首先執行查詢並獲得結果。然後你應該檢查空/計數,並根據該檢查調用添加範圍方法。它也會更具可讀性。

0

添加檢查是否爲空的你真的itm.HeaderName具有訪問該值前值:

where itm.HeaderName.HasValue && // check if value exists 
     xx.CatID == itm.HeaderName.Value && // otherwise here is the problem 
     xx.ProductID == itm.ProductID 
+0

它與視圖檢查失敗.. – NoviceToDotNet

+2

@NoviceToDotNet抱歉,沒有得到你。現在哪裏失敗了,你有什麼錯誤? –

+0

它在productID – NoviceToDotNet

相關問題