I am trying to add data to the User table (after registration). Immediately after user data is added to the user table I wan’t to create row with userID in ‘profile’ table (1:1) and that’s why I use transactions here. But the problem is I can’t get UserId of the user after insert (@@Identity) when code comes to ‘ExecuteScalar()’ line exception that I receive is "Object reference not set to an instance of an object."
string sqlAddUser = string.Format("insert into tbl_users ([UserName],[Email],[Password],[PasswordSalt],[CreatedDate],[IsActivated],[IsLockedOut],[LastLoginDate],[LastLockedOutDate], [NewEmailKey]) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}', '{9}')",
user.UserName, user.Email, user.Password, user.PasswordSalt, user.CreatedDate, user.IsActivated, user.IsLockedOut, user.LastLockedOutDate, user.LastLoginDate, user.NewEmailKey);
SqlCommand cmdAddUser = new SqlCommand(sqlAddUser, conn, transaction);
int result = cmdAddUser.ExecuteNonQuery();
SqlCommand cmdGetLastIdentity = new SqlCommand("SELECT @@IDENTITY", conn, transaction);
int i = (int)cmdGetLastIdentity.ExecuteScalar();
string sqlAddUserProfile = string.Format("insert into tbl_profile (UserId) values ({0})", i);
SqlCommand cmdAddUserProfile = new SqlCommand(sqlAddUserProfile, conn, transaction);
cmdAddUserProfile.ExecuteNonQuery();
transaction.Commit();
return GetUser(username);
}
catch (Exception ex)
{
transaction.Rollback();
}
You can do this in a single statement by using the OUTPUT clause with INSERT, UPDATE, DELETE or MERGE statements.
You can output any database-generated values, and read the values using SqlCommand.ExecuteReader() which will execute the insert and output inserted values as a table.
Note: Don’t use string formating, use sql parameters, otherwise you are vulnerable to sql injection