我怎么能有一个NullReferenceException但我的代码仍然正是我想要的?我怎么能纠正它?

时间:2016-05-30 04:06:27

标签: c# asp.net ssms

我得到了NullReferenceException,但我的代码仍在按照我的意愿行事。怎么会这样?我怎么能摆脱它?我无法弄清楚为什么抛出它。

在线

            int result = (int)sqlCmd.ExecuteScalar();

在方法中:

    public override int AddCustomer(Customer customer)
    {

        try
        {
            SqlCommand sqlCmd = new SqlCommand("INSERT INTO [AXMAP].[Customers] ([LegalEntity], [OldSourceEnvironment], [OldCompanyCode], [OldAcctNum], [AccountNum], [Name], [BusinessUnit], [DefaultDimensionStr]) VALUES (@LegalEntity, @OldSourceEnvironment, @OldCompanyCode, @OldAcctNum, @AccountNum, @Name, @BusinessUnit, @DefaultDimensionStr)");
            sqlCmd.Parameters.AddRange(new SqlParameter[] { new SqlParameter("@LegalEntity", customer.LegalEntity), new SqlParameter("@OldSourceEnvironment", customer.OldSourceEnvironment),
            new SqlParameter("@OldCompanyCode", customer.OldCompanyCode), new SqlParameter("@OldAcctNum", customer.OldAccountNumber), new SqlParameter("@AccountNum", customer.NewAccountNumber),
            new SqlParameter("@Name", customer.BusinessName), new SqlParameter("@BusinessUnit", customer.BusinessUnit), new SqlParameter("DefaultDimensionStr", customer.DefaultDimensionString) });

            sqlCmd.Connection = OpenConnection();
            int result = (int)sqlCmd.ExecuteScalar();
            sqlCmd.Connection.Close();
            return result;
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

我在这个方法中调用AddCustomer:

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            int result = new Customer() { LegalEntity = ddlLegalEntity.Text.Trim(), OldSourceEnvironment = ddlOldSourceEnvironment.Text.Trim(),
                OldCompanyCode = ddlOldCompanyCode.Text.Trim(), OldAccountNumber = txtOldAccountNumber.Text.Trim(), NewAccountNumber = txtNewAccountNumber.Text.Trim(),
                BusinessName = txtBusinessName.Text.Trim(), BusinessUnit = txtBusinessUnit.Text.Trim(), DefaultDimensionString = txtDefaultDimensionString.Text.Trim()}.AddCustomer();

            if (result > 0)
            {
                lvCustomers.EditIndex = -1;
                lblCurrent.Text = "Added Successfully!";
                ddlLegalEntity.Text = string.Empty;
                ddlOldSourceEnvironment.Text = string.Empty;
                ddlOldCompanyCode.Text = string.Empty;
                txtOldAccountNumber.Text = string.Empty;
                txtNewAccountNumber.Text = string.Empty;
                txtBusinessName.Text = string.Empty;
                txtBusinessUnit.Text = string.Empty;
                txtDefaultDimensionString.Text = string.Empty;
            }
            else
            {
                lvCustomers.EditIndex = -1;
                lblCurrent.Text = "Sorry, Add failed.";
            }
        }
        catch (Exception ex)
        {
            lblCurrent.Text = ex.Message;
        }
    }

在行尾:

            int result = new Customer() { LegalEntity = ddlLegalEntity.Text.Trim(), OldSourceEnvironment = ddlOldSourceEnvironment.Text.Trim(),
                OldCompanyCode = ddlOldCompanyCode.Text.Trim(), OldAccountNumber = txtOldAccountNumber.Text.Trim(), NewAccountNumber = txtNewAccountNumber.Text.Trim(),
                BusinessName = txtBusinessName.Text.Trim(), BusinessUnit = txtBusinessUnit.Text.Trim(), DefaultDimensionString = txtDefaultDimensionString.Text.Trim()}.AddCustomer();

客户类看起来像这样:

public class Customer
{

    public string LegalEntity { get; set; }
    public string OldSourceEnvironment { get; set; }
    public string OldCompanyCode { get; set; }
    public string OldAccountNumber { get; set; }
    public string NewAccountNumber { get; set; }
    public string BusinessName { get; set; }
    public string BusinessUnit { get; set; }
    public string DefaultDimensionString { get; set; }

    public int AddCustomer()
    {
        try
        {
            return DataAccessLayer.GetDataAccessLayer().AddCustomer(this);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

}

可能是在客户类中吗?

3 个答案:

答案 0 :(得分:1)

可能是因为(int)sqlCmd.ExecuteScalar()返回null并且你试图将它放入int中。 在执行命令后返回该值,从技术上讲,代码执行您想要的操作,但之后失败。

答案 1 :(得分:1)

根据msdn,当你调用ExecuteScalar时,它“返回查询返回的结果集中第一行的第一列。”所以你需要在Insert Into Command中返回一个值。虽然它没有返回任何试图将Null强制转换为int的东西会抛出NullException。 为了返回插入行的ID,您可以使用以下内容:

INSERT INTO table (name1,name2,name3,...)
OUTPUT Inserted.ID
VALUES(val1,val2,val3,...);

希望这会有所帮助

答案 2 :(得分:1)

您可能需要拨打' ExecuteNonQuery'而不是' ExecuteScalar'。

        int result = sqlCmd.ExecuteNonQuery();
根据MSDN,

ExecuteScalar:

  

执行查询,并返回第一行的第一列   查询返回的结果集。其他列或行是   忽略。

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx

根据MSDN,

ExecuteNonQuery:

  

对连接执行Transact-SQL语句并返回   受影响的行数。

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery%28v=vs.110%29.aspx