If you please help me out I am trying to update a table with a unique constraint which is on all 4 keys (Role_ID, Track_ID, Person_ID, Conference_ID).
Why can I not update it?
error:
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.Exception Details: System.Data.SqlClient.SqlException: Violation of
UNIQUE KEY constraint ‘UK_conferenceRole’. Cannot insert duplicate key
in object ‘dbo.ConferenceRole’. The statement has been terminated.
Code:
var sqlCon7 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string query7 = @"update ConferenceRole set Role_ID =" + 3 + ",Person_ID='" + idp + "'where Conference_ID ='" + conference + "'and Track_ID='" + TrackId + "'";
SqlCommand cmd7 = new SqlCommand(query7, sqlCon7);
cmd7.CommandType = CommandType.Text;
try
{
sqlCon7.Open();
cmd7.ExecuteNonQuery();
sqlCon7.Close();
}
catch (Exception ee)
{
throw ee;
}
Thanks in advance
Your code should look like this – by all means, avoid just stringing together your SQL statements! (that’s the door opener to SQL injection!). Also, with ADO.NET, you should put your connection and command into using-blocks to make sure they get properly disposed when no longer needed:
And this construct here:
is absolutely pointless – all it does is destroy the call stack, e.g. you won’t be able to see where the exception really came from anymore – just leave it out all together, or if you must – use
What the error says it that you’re trying to create a duplicate entry into the table – one with a combination
(Role_ID, Track_ID, Person_ID, Conference_ID)that already exists. That’s the whole point of the unique constraint: to prevent this from happening. So check your table – you must already have an entry in your table that has the same four values as the one you’re trying to update this row to….