没有记录时ExecuteScalar() return 错误"Specified cast is not valid."

ExecuteScalar() return error "Specified cast is not valid." when there is no record

我使用下面的代码计算每个客户的(总发票),对于没有发票的客户,它 return 错误,我尝试用 null 处理错误,但它不起作用。

   public static decimal GetInvoiceTotal(int customerID)
    {
        SqlConnection connection = MMABooksDB.GetConnection();
        string selectStatement
            = "SELECT SUM(InvoiceTotal) "
            + "FROM Invoices "
            + "WHERE CustomerID = @CustomerID";
        SqlCommand selectCommand =
            new SqlCommand(selectStatement, connection);
        selectCommand.Parameters.AddWithValue("@CustomerID", customerID);




        try
        {
            connection.Open();

            if (selectCommand.ExecuteScalar()!=null)
            {
                decimal invoiceTotal = (decimal)selectCommand.ExecuteScalar();
                return invoiceTotal;
            }


            else
            {
                return 0;
            }
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }
    }

您不必调用 ExecuteScalar 两次。

var value = selectCommand.ExecuteScalar();
if(value != DBNull.Value)
{
    return (decimal)value;
}

更新

概括地说,DBNull class 代表一个不存在的值。它与 null 不同,后者表示不存在对对象的引用。因此,当 sql 查询的结果是 NULL 时,ADO.NET(这是您用来访问数据库的技术)返回的值是 DBNull.

更多信息,请查看here