ExecuteScalar()返回错误“;指定的强制转换无效";当没有记录时

本文关键字:quot 无效 转换 记录 返回 错误 ExecuteScalar | 更新日期: 2023-09-27 18:15:36

我使用下面的代码来计算每个客户的(发票总额(,对于没有发票的客户,它返回错误,我试图用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()返回错误“;指定的强制转换无效";当没有记录时

您不必调用ExecuteScalar两次。

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

更新

在粗笔画中,DBNull类表示一个不存在的值。它不同于null,后者意味着没有对对象的引用。因此,当sql查询的结果是NULL时,ADO.NET(用于访问数据库的技术(返回的值是DBNull

欲了解更多信息,请查看此处。