【问题标题】:Checking if the SQL query returns null检查 SQL 查询是否返回 null
【发布时间】:2020-03-01 10:21:01
【问题描述】:

我有问题。我正在从数据库中获取某个列的总和。 但是,在某些情况下,总和应该为 0 -> 如果没有符合条件的记录

在我看来:

<Label Content="{Binding Path=Sum, UpdateSourceTrigger=PropertyChanged}" />

在 ViewModel 我有:

public override void save()
{
    Sum = new Sum(ATMAEntites).Calculate(IdEvent, IdDealer, "Standing");      
}

在我的模型类中:

public int? Calculate(int IdEvent, int IdDealer, string CategoryName)
{
    return (from wydaneSprzedawcy in ATMAEntites.WydaneSprzedawcy
            where wydaneSprzedawcy.Bilety.IdEvent == IdEvent &&
                  wydaneSprzedawcy.IdDealer == IdDealer &&
                  wydaneSprzedawcy.Bilety.CategoryName == CategoryName
            select wydaneSprzedawcy.quantity).Sum();
}

我想在模型中检查查询是否返回 null

【问题讨论】:

  • 如果没有记录与where 表达式匹配,您的代码将为您提供0,但如果ATMAEntites.WydaneSprzedawcy 有时为您提供null 值,请在进入循环之前添加测试:@987654328 @

标签: c# sql entity-framework


【解决方案1】:

我假设 wydaneSprzedawcy.quantity 是 int 且不可为空。然后你可以尝试在选择中添加一个强制转换为 (int?),如下所示:

public int? Calculate(int IdEvent, int IdDealer, string CategoryName)
{
    return
        (
            from wydaneSprzedawcy in ATMAEntites.WydaneSprzedawcy
            where
                wydaneSprzedawcy.Bilety.IdEvent == IdEvent &&
                wydaneSprzedawcy.IdDealer == IdDealer &&
                wydaneSprzedawcy.Bilety.CategoryName == CategoryName
            select (int?)wydaneSprzedawcy.quantity
        ).Sum();
}

现在,如果查询没有返回记录,sum 应该返回 null。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2023-03-21
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2021-08-16
    相关资源
    最近更新 更多