LINQ .SUM() 和可为空的数据库值
我知道为什么会发生这种情况,但是有人可以指出我正确的语法方向吗?
目前我有:
var expense = from e in db.I_ITEM
where e.ExpenseId == expenseId
select e;
return expense.Sum(x => x.Mileage ?? 0);
我的问题是 x.Mileage 的类型为“double?”并且在数据库中有空值。
我得到的错误是:
Exception Details: System.InvalidOperationException: The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
正确的语法是什么?
I know why this is happening but can somebody point me in the right direction of syntax?
Currently I have:
var expense = from e in db.I_ITEM
where e.ExpenseId == expenseId
select e;
return expense.Sum(x => x.Mileage ?? 0);
My problem is that x.Mileage is of type "double?" and has null values in the db.
The error I get is:
Exception Details: System.InvalidOperationException: The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
What would be the correct syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我很惊讶它失败了,但可能工作的另一种方法是简单地对可为空的值求和,然后使用空合并运算符:
当然在 LINQ to Objects 中这可以做到正确的做法是,如果序列中没有非空值,则忽略空值并给出空结果(在空合并运算符之前)。
I'm surprised that fails, but an alternative which might work is simply to sum the nullable values and then use the null coalescing operator:
Certainly in LINQ to Objects this would do the right thing, ignoring null values and giving you a null result (before the null coalescing operator) if there were no non-null values in the sequence.
排除空值怎么样,即
What about excluding the nulls, ie
可以给你意见...
may give you an opinion...
您使用哪个 O/R 映射器以及哪个数据库? (Linq to SQL/实体框架/SQL Server)?
由于表达式在数据库中作为 SQL 语句执行,我认为它无需合并运算符即可工作:
var Expense = from e in db.I_ITEM
其中 e.ExpenseId == 费用Id
选择e;
返回费用.Sum(x => x.Mileage);
Which O/R mapper are you using, and which DB are you using? (Linq to SQL/Entity Framework/SQL Server)?
Since the expression is executed in the DB as a SQL statement, I would think it would work without the coalescing operator:
var expense = from e in db.I_ITEM
where e.ExpenseId == expenseId
select e;
return expense.Sum(x => x.Mileage);
可空字段:
如果计算字段可为空,则无需执行任何特殊操作。只需按原样使用 sum 即可,如下所示:
这里,求和可以为空(双精度?)。如果您使其不可为空,则使用空合并运算符并设置默认值0(零),如下所示:
不可为空字段:
但是,如果计算字段不可为空,那么您需要首先将可空值转换为求和,如下所示:
另外,这里的求和是可以为空的(双精度?)。如果您使其不可为空,则使用空合并运算符,如下所示:
Nullable Field:
If the calculating field is nullable then no need to do anything special. Just use sum as it is, like below:
Here, the summation is nullable (double?). If you make it not nullable then use the null coalescing operator and set a default value 0(zero), like below:
Not Nullable Field:
But, if the calculating field is not nullable, then you need to cast nullable first for summation, like this below:
Also here, the summation is nullable (double?). If you make it not nullable then use the null coalescing operator, like below: