如何使用 IEnumerable<decimal> C# 处理空 return 数据中的异常

How to handle exception in empty return data with IEnumerable<decimal> C#

我正在使用 Dapper 并希望使用存储过程 return 今天的销售额,但如果今天没有销售,它 return 的空值又会引发异常 "'你调用的对象是空的。”在 Query.

如何处理该异常?

使用的代码

public decimal GetAllSaleTotal(string connectionStringName = "POS")
{
    string connectionString = GetConnectionString(connectionStringName);
    using (IDbConnection connection = new SqlConnection(connectionString))
    {
        var result = connection.Query<decimal>("dbo.GetTotalSales", commandType: 
                    CommandType.StoredProcedure).First();
        return result;
    }
}

为什么不使用 try..catch 语句处理异常。

另外,你应该使用 var result = connection.Query<decimal?>("dbo.GetTotalSales", commandType: CommandType.StoredProcedure).FirstOrDefault();

以下是我的处理方式。使用 Take 获取 0 或 1 行,然后检查长度。

public decimal GetAllSaleTotal(string connectionStringName = "POS")
{
    string connectionString = GetConnectionString(connectionStringName);
    using (IDbConnection connection = new SqlConnection(connectionString))
    {
        var result = connection.Query<decimal>
        (
            commandText: "dbo.GetTotalSales", 
            commandType: CommandType.StoredProcedure
        ).Take(1).ToList();
        return result.Count > 0 ? result[0] : 0M;
    }
}