I have this code in my application, and it's working fine. I didn't use SCOPE_IDENTITY as I heard its old method. Can anybody check if I am doing the right method for getting last inserted Record ID ? Will this work If I add a transaction ?
using (SqlCommand com = new SqlCommand("INSERT INTO App_Users (UserName, Description) OUTPUT INSERTED.UserID " +
"VALUES (@pUserName, @pDescription); ", con))
{
com.Parameters.AddWithValue("@pUserName" ,userNameTxt.Text );
com.Parameters.AddWithValue("@pDescription" , userDescription.Text);
int lastID = Convert.ToInt32(com.ExecuteScalar());
foreach (ListViewItem lit in ListView3.Items)
{
HiddenField gid = (HiddenField)lit.FindControl("ListGroupID");
int gidVal = 0;
if (gid != null && gid.Value != null && !Int32.TryParse(gid.Value, out gidVal)) gidVal = 0;
if (gidVal != 0)
{
com.CommandText = "INSERT INTO App_UserGroups (UserID, GroupID) " +
"VALUES ( " + lastID + ", " + gidVal + ")";
com.ExecuteNonQuery();
}
}