【问题标题】:The SqlCommand.ExecuteScalar() function is not returning the Id of the inserted rowSqlCommand.ExecuteScalar() 函数未返回插入行的 Id
【发布时间】:2016-11-27 07:21:25
【问题描述】:
public void Insert(Order order)
{

    SqlConnection con = DACHelper.GetConnection();
    SqlCommand cmd = new SqlCommand(INSERT, 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
        {
            order.Id= Convert.ToInt32(cmd.ExecuteScalar());
            new OrderMailsDAC().Insert(order.Id, order.Mail , tran);
            tran.Commit();
        }
        catch (Exception)
        {
            tran.Rollback();
            throw;
        }
    }
}

然后我在 OrderMails 类的以下 Insert 函数中插入了 order.Id。

public void Insert(int orderId,OrderConfirmationMail mails,SqlTransaction tran)
{
    SqlConnection con = tran.Connection;
    SqlCommand cmd = new SqlCommand(INSERT, con);
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.Transaction = tran;
    cmd.Parameters.AddWithValue("@Mail", mails.Mail);
    cmd.Parameters.AddWithValue("@Order_Id", orderId);
    cmd.ExecuteNonQuery();
}

这里的问题是 order.Id 值在插入 OredrMail 的另一个 Insert 时会在该位置存储零。列是自动递增的,我们存储在 Order 表中的 ad.Id ...

【问题讨论】:

标签: c# asp.net asp.net-mvc-4


【解决方案1】:

ExecuteScalar 返回返回的第一行的第一列。通常,如果我们希望接收单个值,我们只需让过程选择一个值。

在你的程序中声明一个变量

declare @id

然后在您插入之后,

set @id = scope_identity()

然后当程序完成执行时

select @id

您实际上可以将所有这些浓缩为

insert ....whatever
select scope_identity()

我只是倾向于更明确,以防中间的任何其他操作替换 scope_identity() 的值。

【讨论】:

  • 然后我在 OrderMails 类方法 INsert 的以下插入中插入了 order.Id。 public void Insert(int orderId,OrderConfirmationMail mails,SqlTransaction tran) { SqlConnection con = tran.Connection; SqlCommand cmd = new SqlCommand(INSERT, con); cmd.CommandType = System.Data.CommandType.Text; cmd.Transaction = 传输; cmd.Parameters.AddWithValue("@Mail", mails.Mail); cmd.Parameters.AddWithValue("@Order_Id", orderId); cmd.ExecuteNonQuery(); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多