I got the following error for my code:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: The UPDATE statement conflicted with the FOREIGN KEY constraint
"FK_TutorID". The conflict occurred in database "NPTC", table "dbo.Tutor", column 'TutorID'.
This is my code:
// Instantiate a SqlConnection object with the COnnection String read.
SqlConnection conn = new SqlConnection(strConn.ToString());
// Instantiate a sqlcommand object, provide a update sql statement to add
// class to tutor record specified by a classID
SqlCommand cmd = new SqlCommand("
UPDATE TuitionClass
SET TutorID = @tutorID
FROM TuitionClass
INNER JOIN Tutor ON TuitionClass.tutorID = Tutor.tutorID
AND TuitionClassID = @selectedTuitionClassID", conn);
// Define the parameter used in SQL statement, value for the parameter is retrieved
// from class's property
cmd.Parameters.AddWithValue("@tutorID", TutorID);
cmd.Parameters.AddWithValue("@selectedTuitionClassID", tuitionClassID);
// open a Database connection
conn.Open();
// Execute the SQL statement
int count = cmd.ExecuteNonQuery();
// Close database connection
I'm not sure where it has gone wrong because I think my code is correct?
The conflict occurred in database "NPTC", table "dbo.Tutor", column 'TutorID'.this is your issue. You're (probably) attempting to update the TutorID to a value that does not exist from the originating table.AddWithValue()- it can lead to unexpected and surprising results...