c# – 转换为值类型“Double”失败,因为物化值为null

栏目: ASP.NET · 发布时间: 6年前

内容简介:http://stackoverflow.com/questions/15297925/the-cast-to-value-type-double-failed-because-the-materialized-value-is-null

码:

double cafeSales = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd)
    .Sum(x => x.Quantity * x.Price);

错误:

转换为值类型“Double”失败,因为物化值为null.结果类型的通用参数或查询必须使用可空类型.

我已经看到了什么:

The cast to value type ‘Int32’ failed because the materialized value is null

The cast to value type ‘Decimal’ failed because the materialized value is null

我有什么:

double cafeSales = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd)
    .DefaultIfEmpty()
    .Sum(x => x.Quantity * x.Price);

和:

double? cafeSales = db.InvoiceLines
    .Where(x =>
        x.UserId == user.UserId &&
        x.DateCharged >= dateStart &&
        x.DateCharged <= dateEnd)
    .Sum(x => x.Quantity * x.Price);

这两个都不工作.我知道这个问题的原因是该表中没有对我进入的UserId的行.在这种情况下,我宁愿Sum()刚刚返回一个0给我.有任何想法吗?

最佳解决方案
double cafeSales = db.InvoiceLines
                     .Where(x =>
                                x.UserId == user.UserId &&
                                x.DateCharged >= dateStart &&
                                x.DateCharged <= dateEnd)
                     .Sum(x => (double?)(x.Quantity * x.Price)) ?? 0;

http://stackoverflow.com/questions/15297925/the-cast-to-value-type-double-failed-because-the-materialized-value-is-null


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Just My Type

Just My Type

Simon Garfield / Profile Books / 2010-10-21 / GBP 14.99

What's your type? Suddenly everyone's obsessed with fonts. Whether you're enraged by Ikea's Verdanagate, want to know what the Beach Boys have in common with easy Jet or why it's okay to like Comic Sa......一起来看看 《Just My Type》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

随机密码生成器
随机密码生成器

多种字符组合密码