2011-06-01 67 views
0

當這個功能被給予在SQL返回0行我得到下面的錯誤的ID:如何處理返回零行並返回十進制值的linq查詢?

空值不能被分配給具有System.Decimal類型的成員,其爲非空值類型。

修改查詢以防止出現這種情況的最佳方法是什麼?我從不同的表中獲取價值,而不是在這裏查詢,所以我希望能夠處理給它一個「壞」的ID。

public decimal GetSumOfValuesForAccount(Guid companyId) 
    { 
     return (from o in _context.Details 
       where o.CustomerID == companyId 
       select o).Sum(p => p.SomeValue.GetValueOrDefault()); 
    } 

返回錯誤:

回答

4

,你應該能夠要麼回報:

return (from o in _context.Details 
       where o.CustomerID == companyId 
       select o).Sum(p => p.SomeValue) ?? -1.0; 

decimal? temp = (from o in _context.Details 
       where o.CustomerID == companyId 
       select o).Sum(p => p.SomeValue); 
return temp ?? -1.0; 

??運營商將檢查空,如果爲空,返回下一個值。

+0

我知道有關空合併運算符,但它仍然失敗。但基於您的評論,我在使用它時刪除了GetValueOrDefault,它可以工作。不知道爲什麼這造成了差異。 – caschw 2011-06-02 03:11:26

+1

@ Speedy2171 - 這是因爲你不能在空引用上執行像'.GetValueOrDefault()'這樣的操作。這意味着沒有滿足條件的'行',並且您需要讓Linq自己處理它。 – Brett 2011-06-02 12:21:59