2016-07-10 37 views
0

我得到這個錯誤,我不知道如何解決它。值不能爲空。參數名稱:Asp.net中的源代碼

堆棧跟蹤:

[ArgumentNullException:值不能爲空。參數名稱:源] System.Linq.Enumerable.FirstOrDefault(IEnumerable'1源,Func'2 謂詞)4358562

eCommerce.Services.BasketService.addToBasket(HttpContextBase HttpContext的,的Int32的productid,的Int32量)在 E:\ projects \ C#\ eCommerce \ eCommerce.Services \ BasketService.cs:51
eCommerce.WebUI.Controllers.HomeController.AddToBasket(Int32 id)in E:\ projects \ C#\ eCommerce \ eCommerce.WebUI \ Controllers \ HomeController.cs:34

這是代碼:

public bool addToBasket(HttpContextBase httpcontext, int productid, int quantity) 
{ 
    bool success = true; 

    Basket basket = GetBasket(httpcontext); 

    // this line throws the error 
    BasketItem item = basket.BasketItems.FirstOrDefault(i => i.ProductId == productid); 

    if (item == null) 
    { 
     item = new BasketItem() 
      { 
       BasketId = basket.BasketId, 
       ProductId = productid, 
       Quantity = quantity 
      }; 
     basket.BasketItems.Add(item); 
    } 
    else 
    { 
     item.Quantity = item.Quantity + quantity; 
    } 

    baskets.Commit(); 

    return success; 
} 

請幫助我,我一直在堅持了一段時間,現在

+1

檢查'BasketItems'不是'null' –

回答

0

不知道如果GetBasket()總是返回一個值或不是,我會假設它可能不總是返回一個值,所以我們檢查爲空。此外,basket可能不爲空,但BasketItems可能是這樣,讓我們​​來檢查該對象是否有任何值。

如果兩個條件都成立,那麼我們繼續並執行其餘的代碼。如果不是,那麼我們返回false。您也可以在此處創建一條消息,以記錄或返回有關籃子爲空/空的用戶。

public bool addToBasket(HttpContextBase httpcontext, int productid, int quantity) 
     { 
      bool success = true; 

      Basket basket = GetBasket(httpcontext); 

      // Not sure if GetBasket always returns a value so checking for NULLs 
      if (basket != null && basket.BasketItems != null && basket.BasketItems.Any()) 
      { 
       BasketItem item = basket.BasketItems.FirstOrDefault(i => i.ProductId == productid); 

       if (item == null) 
       { 
        item = new BasketItem() 
        { 
         BasketId = basket.BasketId, 
         ProductId = productid, 
         Quantity = quantity 
        }; 
        basket.BasketItems.Add(item); 
       } 
       else 
       { 
        item.Quantity = item.Quantity + quantity; 
       } 

       baskets.Commit(); 

       success = true; 
      } 
      else 
      { 
       // Basket is null or BasketItems does not contain any items. 
       // You could return an error message specifying that if needed. 
       success = false; 
      } 

      return success; 
     } 
+0

STIL因此未工作,我在該行'如果有同樣的錯誤(籃!= NULL && basket.BasketItems.Any())' –

+1

您還需要' && basket.BasketItems!= null'。你的錯誤是因爲'BasketItems'爲'null' –

+0

更新了上面的例子,以便在basket上查找null .BasketItems –

1

提領時,一定要檢查空值。在GetBasket沒有返回空值的檢查中,那個basket.basketitems在提領它之前不爲空,等等。

相關問題