gpt4 book ai didi

c# - 转换为值类型 'Double' 失败,因为具体化值为 null

转载 作者:IT王子 更新时间:2023-10-29 04:22:41 27 4
gpt4 key购买 nike

代码:

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;

关于c# - 转换为值类型 'Double' 失败,因为具体化值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15297925/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com