1

我正在尝试获取最后一个插入函数生成的 ID。我对范围和会话知之甚少。但是通过阅读博客和其他资源,我明白,我应该使用 Scope_Identity() 函数。但我得到空值。这是我的代码:

 public int InsertUser(string username, string gender, string agegroup, string email, int partnerID, string userType)
{
    try
    {
        string query = "Insert into tblUser (username,gender,agegroup,email,partnerid,usertype) values (@username,@gender,@age,@email,@partnerid,@usertype)";
        SqlCommand cmd = new SqlCommand(query, _dbConnection.getCon());
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@username", username);
        cmd.Parameters.AddWithValue("@gender", gender);
        cmd.Parameters.AddWithValue("@age", agegroup);
        cmd.Parameters.AddWithValue("@email", email);
        cmd.Parameters.AddWithValue("@partnerid", partnerID);
        cmd.Parameters.AddWithValue("@usertype", userType);
        if (cmd.ExecuteNonQuery() > 0)
        {
            query = "select scope_identity() as id";
            cmd = new SqlCommand(query, _dbConnection.getCon());
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);// dt is showing no value in it
            return 1;// This should return ID

        }
        else {
            return -1;
        }

    }
    catch (Exception e) {
        throw e;
    }
}

我怎样才能做到这一点?

4

1 回答 1

4

尝试附加SELECT scope_identity()到您的第一个查询,然后使用var identity = cmd.ExecuteScalar()而不是运行捕获身份cmd.ExecuteNonQuery()

于 2013-08-12T04:06:12.847 回答