Having initially tested in Sql
the following command
INSERT INTO UserActivationDB (UserId, ActivationCode) VALUES (3,NEWID())
that works perfectly, I have been attempting to adjust a C# method
to circumvent an Exception.
private void Checkmail(int userId)
{
string constr = ConfigurationManager.ConnectionStrings["RegisterDB"].ConnectionString;
string activationCode = Guid.NewGuid().ToString();
using (SqlConnection con = new SqlConnection(constr))
{
//using (SqlCommand cmd = new SqlCommand("INSERT INTO UserActivationDB VALUES(@UserId, @ActivationCode)"))
using (SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT UserActivationDB ON INSERT INTO UserActivationDB VALUES(@UserId, NEWID()) SET IDENTITY_INSERT UserActivationDB OFF"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@UserId", userId);
//cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}```
**Error message**
```System.Data.SqlClient.SqlException
HResult=0x80131904
Message=An explicit value for the identity column in table UserActivationDB can only be specified when a column list is used and IDENTITY_INSERT is ON.
Source=.Net SqlClient Data Provider
StackTrace:
<Cannot evaluate the exception stack trace>
Ps: As I was stuck in keeping activationCode
as string
and inserting it into a uniqueidentifier
type in the UserActivationDB
table (merely 2 columns) , I 've commented it and substitute it with NEWID()
but I am still encountering similar issues at cmd.ExecuteNonQuery()
;
Thus a feedback on such issues, particularly on the cmd = new SqlCommand(...)
object, would highly be appreciated.
Best,
User contributions licensed under CC BY-SA 3.0