2017-01-03 60 views
1

我想在下面的代碼使用的總和,但我得到的錯誤:LINQ:失敗,因爲物化值爲null

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

Product_Order: 
    ---------------- ----------- --------- 
    | ProductId | OrderId | Quantity | 
    ---------------- ----------- --------- 

我得到的錯誤在「let quantity

var fullInfo = (from product in allProdcts 
       let quantity = db.Product_Order.Where(x=> x.ProductId == product.ID).Sum(x => x.Quantity) 
       select new ReportVm 
        {       
         ProductId = product.ID, 
         ProductName = product.Name, 
         AmountProduct = quantity, 
         TotPrice = (quantity)*(product.Price) 
        }).ToList(); 

這是我Product_Order表(MM關係):

Product_Order: 
    ---------------- ----------- --------- 
    | ProductId | OrderId | Quantity | 
    ---------------- ----------- --------- 

任何想法如何解決這個問題?

+0

請將'Product_Order'自動生成的POCO類添加到您的問題中。如何定義'Quantity'屬性很重要('int'或'int?'), – Sefe

+0

@M.Wiśnicki正如我理解的那樣,如果代碼爲空,代碼會給出值0? – fagol

+0

@M.Wiśnicki我使用該代碼得到相同的錯誤。但只是加入'(int?)'沒有'??'沒有任何錯誤(但我仍然需要值爲0,如果爲空)。編輯:'??'不會與這段代碼一起工作,我在嘗試這個問題之前就試過了。但它在該代碼之外工作。其他解決方案? – fagol

回答

4

您需要允許空值爲Quantity,您可以使用??表達式實現它,並在使用Sum()時將其轉換爲int?

.Sum(x => (int?)x.Quantity)??0 

您的查詢應該像

var fullInfo = (from product in allProdcts 
      let quantity = db.Product_Order.Where(x => x.ProductId == product.ID).Sum(x => (int?)x.Quantity)??0 
      select new ReportVm 
      { 
       ProductId = product.ID, 
       ProductName = product.Name, 
       AmountProduct = quantity, 
       TotPrice = (quantity)*(product.Price) 
      }).ToList(); 
+0

如果'Quantity'是'int',將其轉換爲'int?'不會改變和絃,並且如果是'int?'類型,則不需要轉換。 – Sefe

1

不得使用聚合函數在一個空的集合返回非空類型。在你的情況下,當db.Product_Order上的where子句不返回任何元素時,Sum()失敗。以下解決方案中,將0定義爲默認值,應該可以工作:

var fullInfo = (from product in allProdcts 
       let productOrder = db.Product_Order.Where(x => x.ProductId == product.ID) 
       let quantity = productOrder.Any() ? productOrder.Sum(x => x.Quantity) : 0 
       select new ReportVm 
       { 
        ProductId = product.ID, 
        ProductName = product.Name, 
        AmountProduct = quantity, 
        TotPrice = (quantity) * (product.Price) 
       }).ToList(); 
相關問題