static void MenuInsert() { int temp = 0; Menu.MenuSubMenu(); while (!Int32.TryParse(Console.ReadLine(), out temp)) { Console.WriteLine("-- Wrong input --"); } switch (temp) { case 1: Inserts.InsertCourse(Inserts.AddCourse()); break; case 2: Inserts.InsertStudent(Inserts.AddStudent()); break; case 3: Inserts.InsertTrainer(Inserts.AddTrainer()); break; case 4: Inserts.InsertAssignment(Inserts.AddAssignment()); break; case 5: Inserts.InsertStudentPerCourse(Inserts.AddStudentPerCourse()); break; case 6: Inserts.InsertTrainerPerCourse(Inserts.AddTrainertPerCourse()); break; case 7: Inserts.InsertAssignmentPerStudentPerCourse(Inserts.AddAssignmentPerCourse()); break; case 8: RunMenu(); break; default: Console.WriteLine("Wrong Input"); break; } }
public static void InsertAssignmentPerStudentPerCourse(AssignmentPerStudentPerCourse apc) { var connectionString = Properties.Settings.Default.connectionString; using (SqlConnection con = new SqlConnection(connectionString)) { string query = @"INSERT INTO Assignment_Per_Course VALUES(@CourseId, @AssignmentId)INSERT INTO Student_Per_Course VALUES(@StudentId,@CourseId)"; SqlCommand cmd = new SqlCommand(query, con); //Pass values to Parameters cmd.Parameters.AddWithValue("@CourseId", apc.CourseId); cmd.Parameters.AddWithValue("@AssignmentId", apc.AssignemntId); cmd.Parameters.AddWithValue("@StudentId", apc.StudentId); try { con.Open(); cmd.ExecuteNonQuery(); Console.WriteLine("Records Inserted Successfully"); Menu.RunMenu(); } catch (SqlException e) when(e.Number == 2627) //Exception this relationship already exists { Console.WriteLine("\n Wrong\n The combination already exists try again"); Inserts.InsertAssignmentPerStudentPerCourse(Inserts.AddAssignmentPerCourse()); } catch (SqlException e) when(e.Number == 547) //Exception the id doesn't exist { Console.WriteLine("\n Wrong\n The Id does not exist try again"); Inserts.InsertStudentPerCourse(Inserts.AddStudentPerCourse()); } catch (SqlException e) { Console.WriteLine("Error Generated. Details: " + e.ToString()); } finally { con.Close(); Console.ReadKey(); } } }