Search code examples
c#dapper

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

Solution

  • 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();