【问题标题】:How to handle a linq query that returns zero rows and have it return decimal value?如何处理返回零行并返回十进制值的 linq 查询?
【发布时间】:2011-06-01 21:07:25
【问题描述】:

当给这个函数一个在 SQL 中返回 0 行的 id 时,我得到以下错误:

null 值不能分配给 System.Decimal 类型的成员,该类型是不可为 null 的值类型。

修改查询以防止这种情况的最佳方法是什么。我从一个不同的表中提取值而不是在这里查询,所以我希望能够处理给它一个“坏”的 ID。

    public decimal GetSumOfValuesForAccount(Guid companyId)
    {
        return (from o in _context.Details
                where o.CustomerID == companyId
                select o).Sum(p => p.SomeValue.GetValueOrDefault());
    }

返回错误:

【问题讨论】:

    标签: c# linq linq-to-sql


    【解决方案1】:

    你应该可以返回:

    return (from o in _context.Details
                    where o.CustomerID == companyId
                    select o).Sum(p => p.SomeValue) ?? -1.0;
    

    decimal? temp = (from o in _context.Details
                    where o.CustomerID == companyId
                    select o).Sum(p => p.SomeValue);
    return temp ?? -1.0;
    

    ?? 运算符将检查是否为 null,如果为 null,则返回下一个值。

    【讨论】:

    • 我知道空合并运算符,但它仍然失败。但是根据您的评论,我在使用 GetValueOrDefault 时删除了它并且它可以工作。不知道为什么会有所不同。
    • @Speedy2171 - 这是因为您不能对空引用执行像 .GetValueOrDefault() 这样的操作。这意味着没有满足您条件的“行”,您需要让 Linq 自己处理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 2019-11-14
    相关资源
    最近更新 更多