简体   繁体   English

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

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

I am using Dapper and want to return Today's Sales amount using a Stored Procedure but if there is no sale for today, it returns empty values which in turn throws an exception "'Object reference not set to an instance of an object."我正在使用 Dapper 并想使用存储过程返回今天的销售额,但如果今天没有销售,它会返回空值,从而引发异常“'对象引用未设置为对象的实例。” at the line with the Query .在与Query的行。

How to handle that exception?如何处理那个异常?

Code Used使用的代码

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;
    }
}

Why don't you handle the exception using try..catch statement.为什么不使用 try..catch 语句处理异常。

Also, you should use var result = connection.Query<decimal?>("dbo.GetTotalSales", commandType: CommandType.StoredProcedure).FirstOrDefault();此外,您应该使用var result = connection.Query<decimal?>("dbo.GetTotalSales", commandType: CommandType.StoredProcedure).FirstOrDefault();

Here's how I might handle it.这是我可以处理的方法。 Use Take to get 0 or 1 rows, then check the length.使用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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM