Reputation:
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?
Upvotes: 2
Views: 87
Reputation: 3643
You passed an invalid parameterer here:
cmd.Parameters.AddWithValue("@tutorID", TutorID);
The TutorID
does not match a Tutor
in the database.
Upvotes: 4