我正在尝试获取最后一个插入函数生成的 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;
}
}
我怎样才能做到这一点?