2013-01-08 67 views
4

我有以下LINQ -LINQ錯誤 - 法 '點心',不支持

var quantity = (from p in context.StoreInventory 
         where p.BookId== BookId 
           && p.StoreAddress == StoreAddress 
         select p).Sum(i => i.Quantity); 

我收到錯誤 -

的方法 '點心',不支持

任何人都可以告訴我原因和所需的更改。

+1

它是實體的linq嗎?看看[這裏](http://msdn.microsoft.com/en-us/library/bb738550.aspx) – digEmAll

+0

@digEmAll是的,它是 – RTRokzzz

回答

11
var quantity = (from p in context.StoreInventory 
         where p.BookId== BookId 
           && p.StoreAddress == StoreAddress 
         select p.Quantity).Sum(); 

這應該工作 - 在'Quality'列,這是使用select聲明採取執行總和。這是因爲LINQ to Entities不支持Sum(expression),但標準的Sum()是。

整個工作應該由數據庫完成,所以應用程序不會檢索行 - 只有單個數字。

+0

+1正確答案,這不會帶來計算內存 –

+0

@Marcin:Gr888答案...它的工作。謝謝 – RTRokzzz

2

在調用Sum將查詢轉換爲集合之前,使用Enumerable.ToList

var quantity = (from p in context.StoreInventory 
         where p.BookId== BookId 
           && p.StoreAddress == StoreAddress 
         select p).ToList().Sum(i => i.Quantity); 

編輯:這將使所有的行,將適用這是不這樣做的有效方式的總和。由於您需要總結數量,因此您可以選擇質量而不是行。

var quantity = (from p in context.StoreInventory 
         where p.BookId== BookId 
           && p.StoreAddress == StoreAddress 
         select p.Quantity).Sum(); 
+4

這將強制從數據庫中獲取所有行,並根據應用程序計算總和。 – MarcinJuraszek

相關問題