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."}

  • what exactly is the problem then ?! - Bald
  • you need to understand what key gave the exception - Vardan Vardanyan
  • @ des1roer if translate.google.ru was not mistaken, then Armenian, if I understood correctly, are you trying to write something for a hotel, and your system should not allow you to register several guests in one room? - Bald
  • If you give appropriate names to the constraints of the Primary Key, then the names in the error message will tell you where the exception occurred. - msi
  • @ msi and how to give names? - Vardan Vardanyan

1 answer 1

how you do it:

When you create an instance of a child you create parents at this point, an exception may arise that you want to catch and inform the user. if you do this, then check the presence in the database before attempting to create something like this:

 var mother = //создаете объект; var result = db.Mothers.Where()//делаете запрос к бд if (result.Count()==0) db.Mothers.Insert();//вставляете только в случае отсутствия в бд; //либо делаете блок else в котором информируете пользователя 

similarly check the second parent.

the disadvantages of creating parents with a child right away in this approach are yours: a typo, and now we have duplication, this of course can be avoided by writing validation logic, but it is better to fill reference books with a narrow circle of people

I did not fully understand the logic of your application, I will try to write as I did

 public class Mother { public int Id {get;set;} //прочие поля } public class Father { public int Id {get;set;} //прочие поля } public class Child { public int Id {get;set;} public int MotherId {get;set;} public int FatherId {get;set;} } 

Mother and Father filled as necessary from separate forms plus logic in order to avoid duplication ie these are reference books;

Child I would do like this:

the form in which the child is created, the parents are selected from the list filled earlier, plus some additional information, i.e. before creating a child in the case of a new / new parent, fill out the reference book and only then create a child .

PS: if you decide to leave it all the same then you can analyze the text of the exception that occurred

UPD .:

In the text that was shown, you can see that an exception occurs when you try to add a duplicate entry to dbo.Animals and the entry id is specified.

The easiest option is something like this:

 try {} catch(Exception ex) { if(ex.Message.Contains("Animals")) { } else if(ex.Message.Contains("MotherAnimals")) { } //ну и так далее } 

But still, I would recommend adding a bit of logic: i. Before adding, check for availability in the database

  • @ Bald56rus and how to analyze this text ?? I don’t want to change the whole program for the sake of it, I think I already got my own questions, but if it's not difficult you can write the code? - Vardan Vardanyan
  • @VardanVardanyan updated the answer - Bald