5

我有以下 LINQ to SQL 查询:

var inTransitStocks = orderHistories.Where(oh => oh.Shipped_Qty > 0)
                                    .Select(oh => oh.Shipped_Qty); //.ToList();
var inTransitStock = (int)inTransitStocks.Sum();

没有ToList电话,我就得到了以下异常Sum()

不能将 null 值分配给 System.Double 类型的成员,这是不可为 null 的值类型。

如果我添加一个.ToList()之前的总和(如评论中所示),我不会收到错误消息。

为什么我首先会收到错误消息?Shipped_Qty不为空,并且数据库中不存在该字段中的空数据)

为什么要添加ToList()修复程序?


执行的 sql 查询如下(查询比上面更多):

SELECT [t0].[Shipped Qty]
FROM [dbo].[Order History] AS [t0]
WHERE ([t0].[Shipped Qty] > @p0) AND ([t0].[CUST_ID] = @p1) AND ([t0].[SHIP_TO_ID] = @p2) AND ([t0].[Item] = @p3) AND (([t0].[DT_LST_SHP] >= @p4) OR (UNICODE([t0].[LN_STA]) = @p5))

不返回任何结果。

4

3 回答 3

6

原因如下:

如果没有ToList对数据库执行以下查询:

select SUM(Shipped_Qty) from orderHistories where Shipped_Qty > 0;

If there are no rows matching this criteria, the result of this query is not 0 but NULL.

With ToList the following query gets executed:

select Shipped_Qty from orderHistories where Shipped_Qty > 0;

The result (no rows) will be put into a list. The result is an empty list. On that empty list you execute the LINQ to Objects extension method Sum. The sum of an empty list is 0 and NOT null.

So basically: Different semantics lead to different results.

于 2012-09-05T07:30:31.640 回答
0

After you do the ToList() you are using the Linq-To-Objects implementation of Sum.

Before you do ToList() the Sum operation is being aggregated into the Linq-To-Sql query.


To find out why the Linq-To-Sql fails, follow Daniel Hilgath's approach.

于 2012-09-05T07:31:53.230 回答
0

all was said but let me reformulate : this is because of the magic of var!

Without ToList() var <=> DbQuery
With ToList() var <=> List<Double>

The Sum function does not have the same behaviour on the two types...

于 2012-09-05T07:40:25.743 回答