在C#和SQL中更新记录并返回已更新记录的ID

时间:2018-07-22 14:30:18

标签: c# sql ado sqlparameters

我写了一段代码来插入一行并将插入的行ID返回给该函数的调用点。现在,我需要编写代码来更新记录,并需要获取更新记录的ID。

如何在C#中做到这一点?寻找与插入方法相同的方式而不使用输出参数。

我的插入方法如下:

public Int64 addNewService(Service newService)
    {
        con = new DbConnection();
        string query = "INSERT INTO [Service] (Description) VALUES(@Description) SELECT CAST(SCOPE_IDENTITY() AS BIGINT);";
        Dictionary<string, object> sqlParameters = new Dictionary<string, object>();
        sqlParameters.Add("@Description", newService.Description);
        return con.putDataAndGetId(query, sqlParameters);
    }

PutDataAndGetIdMethod:

        public Int64 putDataAndGetId(string _query, Dictionary<string, object> sqlParameters)
    {
        _cmd = CreateSqlCommand(_query, sqlParameters);
        Int64 id;
        openConnection();
        id = (Int64)_cmd.ExecuteScalar();
        closeConnection();
        return id;
    }

CreateSqlCommand方法:

 private SqlCommand CreateSqlCommand(string commandText, Dictionary<string, Object> sqlParameters)
    {
        SqlCommand command = new SqlCommand();
        command.Connection = _con;
        command.CommandText = commandText;
        command.CommandType = CommandType.Text;
        command.CommandTimeout = 0;
        if (sqlParameters != null)
        {
            foreach (KeyValuePair<string, Object> item in sqlParameters)
            {
                SqlParameter parameter = new SqlParameter(item.Key, item.Value);
                command.Parameters.Add(parameter);
            }
        }
        command.CommandText = commandText;
        return command;
    }

我尝试按照上述代码更新记录。但是SELECT CAST(SCOPE_IDENTITY() AS BIGINT);代码不会通过执行id = (Int64)_cmd.ExecuteScalar();行代码来返回更新记录的ID。

如何在更新操作中使用此方法结构。

谢谢。

0 个答案:

没有答案
相关问题