LINQ错误 - 不支持方法'Sum'

时间:2013-01-08 09:04:29

标签: c# linq linq-to-entities

我正在关注linq -

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

我收到错误 -

  

不支持“Sum”方法

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

2 个答案:

答案 0 :(得分: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()是。{/ p>

整个工作应该由数据库完成,因此应用程序不会检索任何行 - 只需一个数字。

答案 1 :(得分: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);

编辑:这将带来所有行并将应用总和,这不是有效的方法。由于您需要总结数量,您可以选择quanity而不是row。

var quantity = (from p in context.StoreInventory
                         where p.BookId== BookId
                                && p.StoreAddress == StoreAddress
                         select p.Quantity).Sum();
相关问题