SqlCommand.ExecuteScalar()返回null

时间:2016-07-25 07:03:35

标签: sql-server asp.net-mvc

我有这段代码。

public void Insert(Order order)
{
        SqlConnection con = DACHelper.GetConnection();

        SqlCommand cmd = new SqlCommand("Insert into Orders(Category_Id,Item_Id)Values(@Category_Id,@Item_Id)", con);
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Category_Id", order.Category.Id);
        cmd.Parameters.AddWithValue("@Item_Id", order.Item.Id);

        con.Open();

        using (con)
        {
            SqlTransaction tran = con.BeginTransaction();
            cmd.Transaction = tran;

            try
            {
                int orderId = Convert.ToInt32(cmd.ExecuteScalar());

                new OrderMailsDAC().Insert(orderId, order.Mail , tran);
                tran.Commit();
            }
            catch (Exception ex)
            {
                tran.Rollback();
                throw ex;
            }
        }
}

public void Insert(int orderId,OrderConfirmationMail mails,SqlTransaction tran)
{
    SqlConnection con = tran.Connection;

    SqlCommand cmd = new SqlCommand("Insert into OrderMails(Mail,Order_Id)Values(@Mail,@Order_Id)", con);
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.Transaction = tran;
    cmd.Parameters.Add("@Mail", SqlDbType.VarChar).Value=mails.Mail;
    cmd.Parameters.Add("@Order_Id",SqlDbType.Int).Value=orderId;

    cmd.ExecuteNonQuery();
}

这里的问题是

int orderId = Convert.ToInt32(cmd.ExecuteScalar());
除了正确存储的Id之外,

返回null。

请帮我解决这个问题

3 个答案:

答案 0 :(得分:0)

您必须设置输出参数以在ExecuteScalar中获取新记录值

答案 1 :(得分:0)

ExecuteScalar意味着它将返回结果集的第一个单元格。据此,现在看看你的命令代码:

"Insert into Orders(Category_Id,Item_Id)Values(@Category_Id,@Item_Id)"

你看,它只是在你的订单表中插入一条记录,就是它,没有任何回报。

因此,如果我们想要返回OrderId,以防表中有该列,则应修改命令以返回该数据。

我建议这样的事情

"Insert into Orders(Category_Id,Item_Id)Values(@Category_Id,@Item_Id); SELECT SCOPE_IDENTITY();"

答案 2 :(得分:0)

使用SCOPE_IDENTITY()

  public void Insert(int orderId,OrderConfirmationMail mails,SqlTransaction tran)
     {
SqlConnection con = tran.Connection;

SqlCommand cmd = new SqlCommand("Insert into OrderMails(Mail,Order_Id)Values(@Mail,@Order_Id) " +
                         "SELECT SCOPE_IDENTITY()";, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Transaction = tran;
cmd.Parameters.Add("@Mail", SqlDbType.VarChar).Value=mails.Mail;
cmd.Parameters.Add("@Order_Id",SqlDbType.Int).Value=orderId;

int insertedId = (int) cmd.ExecuteNonQuery();
}