For Primary Key, I wrote this code to handle exceptions. But I have three tables and three unique keys. How to understand which of them gave this exception to mark this area in red?
try { } catch (SqlException ex) { if (ex.Number == 2627) { MessageBox.Show("Տվյալ համարի կենդանի արդեն գրանցված է..."); } }
here is the DB construction
CREATE TABLE Animals( number int NOT NULL, //прочие поля motherNumber int , FOREIGN KEY (motherNumber) REFERENCES MotherAnimal(motherNumber), fatherNumber int , FOREIGN KEY (fatherNumber) REFERENCES FatherAnimal(fatherNumber), CONSTRAINT PK_number PRIMARY KEY (number) ) Create Table MotherAnimal( motherNumber int not null, //Прочие поля CONSTRAINT PK_motherNumber PRIMARY KEY (motherNumber) ) Create Table FatherAnimal( fatherNumber int not null, //Прочие поля CONSTRAINT PK_fatherNumber PRIMARY KEY (fatherNumber) )
C # code
private void button1_Click(object sender, EventArgs e) { BandivanKatDataContext db = new BandivanKatDataContext(); try { MotherAnimal newMotherAnimal = new MotherAnimal(); // db.MotherAnimal.InsertOnSubmit(newMotherAnimal); db.SubmitChanges(); // FatherAnimal newFatherAnimal = new FatherAnimal(); db.FatherAnimal.InsertOnSubmit(newFatherAnimal); db.SubmitChanges(); Animals newAnimal = new Animals(); db.Animals.InsertOnSubmit(newAnimal); db.SubmitChanges(); // } catch (SqlException ex) { if (ex.Number == 2627) { if (ex.Source == "PK_number") { MessageBox.Show("..."); textBox1.BackColor = Color.Red; } else if (ex.Source == "PK_motherNumber") { MessageBox.Show("..."); textBox8.BackColor = Color.Red; } else if (ex.Source == "PK_fatherNumber") { MessageBox.Show("..."); textBox11.BackColor = Color.Red; } } } }
{"Broken \" PK_number \ "PRIMARY KEY constraint. Cannot insert duplicate key into \" dbo.Animals \ "object. Repeating key value: (1). \ R \ nThe execution of this instruction was interrupted."}