简体   繁体   中英

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." at the line with the 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.

Also, you should use 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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