2014-01-28 41 views
0

我有一些代碼是這樣的:由於物化值爲空,因此值類型爲「Int32」的轉換失敗。請幫助我如何固定它

public int GetCount() 
    { 
     // Get the count of each item in the cart and sum them up 
     var s = BikesDB.ShoppingCartItems.Where(cart => cart.ShoppingCartID == ShoppingCartID1).Select(cart => cart.Quantity).Sum(cart => cart); 

     // Return 0 if all entries are null 
     return s; 
    } 

在這裏,我得到了什麼,當我調試:

The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type. 

我非常欣賞從你的任何問題,非常感謝!

+0

嘗試刪除總和部分,看看它是否工作,猜測其中一個項目是空的,並試圖將其總和試圖轉換爲int –

回答

2

Sum之前,添加DefaultIfEmpty(0)到鏈:

var s = BikesDB.ShoppingCartItems 
       .Where(cart => cart.ShoppingCartID == ShoppingCartID1) 
       .Select(cart => cart.Quantity) 
       .DefaultIfEmpty(0) 
       .Sum(cart => cart); 

,當你有任何元素,它會處理此案。

1

我相信,你需要在哪裏打電話篩選出的項目,其中數量爲空拋出,即

var s = BikesDB.ShoppingCartItems.Where(cart => cart.ShoppingCartID == ShoppingCartID1 && cart.Quantity.HasValue).Sum(cart => cart.Quantity.Value); 
0

對於誰是得到錯誤(可能是因爲你使用的是加入)人:

「不包含‘DefaultIfEmpty’的定義」

var s = BikesDB.ShoppingCartItems 
       .Where(cart => cart.ShoppingCartID == ShoppingCartID1) 
       .Select(cart => cart.Quantity) 
       .Sum(cart => cart) 
       .GetValueOrDefault(0); 

在我來說,我需要它,因爲這個j的oin:

return Orders 
    .Join(
    OrderLogisticss, 
    o => o.ID, 
    ol => ol.OrderID, 
    (o, ol) => new { Order = o, OrderLogistics = ol }) 
    .Where(x => x.OrderLogistics.DepartureDate == date) 
    .Sum(x => x.Order.NumberOfCarts) 
    .GetValueOrDefault(0); 
相關問題