// function example to update user password public static void changePasswordUser(int id, string newPassword) { try { DbContextDal dal = new DbContextDal(); // פעולת חיפוש משתנה // יצירת אובייקט משתמש כדי שניקלוט אליו משתמש קיים מהבסיס נתונים User user; // מציאת משתמש לפי מפתח ראשי user = dal.users.Find(id); // או // מציאת סטודנט לפי סינון , ובחירה של הראשון או דיפולטיבי user = dal.users.Find(id); // שינוי נתונים באובייקט user.password = newPassword; // שמירת מצב השינויים dal.SaveChanges(); } catch (Exception ex) { MessageBox.Show("" + ex.ToString()); } }
// function to add grade for the first time to student who learn some course public void addGradeToStudent(int idStudent, int idCourse, int grade) { // Get connection to DB DbContextDal context = new DbContextDal(); // get Course by id Course course = context.courses.Find(idCourse); // get student by id Student student = context.students.Find(idStudent); // create new enrollment - connect student and course, adding new grade Enrollment enrollment = new Enrollment() { Student = student, Course = course }; // add grade for the course the student learn enrollment.Grade = grade; // connect enroll to student student.Enrollments.Add(enrollment); // connect enroll to course course.Enrollments.Add(enrollment); // add new enrollment to database context.Enrollments.Add(enrollment); // save the database's change context.SaveChanges(); }
private void btn_update_Click(object sender, EventArgs e) { if (courseSelected != null) { try { setUpdateState(); dal.SaveChanges(); btn_search_Click(sender, e); MessageBox.Show("The course detail updated!"); } catch (DbEntityValidationException ex) { //MessageBox.Show("Db Entity Validation Exception"); string str = "" + ex.Source + " : " + ex.GetType() + "\n-----------------------------------------------------------------------------------------------------\n" + "Message: " + ex.Message + "\n\nExplain & solution:\nThe problem is that you try to insert an object with data that does not fit the limitations of the data base to these object fields.\n\nThe following is a list of the incorrect features:\n"; foreach (var entityValidationErrors in ex.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { str += ("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage + "\n"); } } MessageBox.Show(str); } catch (Exception eu) { MessageBox.Show("Error: \n\n" + eu.ToString()); } } }
private void CreateStudyForm() { bool createForm = true; DbContextDal dal = new DbContextDal(); int ID = int.Parse(comboBox_IDs.SelectedItem.ToString()); StudentStudyForm StudyForm = new StudentStudyForm() { ID = ID, FormCreateDate = DateTime.Today, ValidationDate = dateTimePicker1.Value.Date }; StudentStudyForm SF = dal.StudentsStudyForms.Where(x => x.ID == ID).FirstOrDefault(); if (SF != null) { DialogResult result = MessageBox.Show("Student allready have study form, do you want to change it?", "caption", MessageBoxButtons.YesNo); if (result == DialogResult.No) { createForm = false; } if (createForm == true) { dal.Entry(SF).CurrentValues.SetValues(StudyForm); dal.SaveChanges(); MessageBox.Show("Fee study added"); } else { MessageBox.Show("Fee study not added"); } } else { dal.StudentsStudyForms.Add(StudyForm); dal.SaveChanges(); MessageBox.Show("Study form added"); } }
// function example to adding new user and student public static bool createAdminUser() { try { // פעולת הוספה DbContextDal dal = new DbContextDal(); // יצירת אובייקט משתמש וסטודנט כדי להכניס לבסיס נתונים User user = new User(0, "admin", "Admin", "admin"); Admin admin = new Admin(); admin.ID = 0; // !שדה חובה admin.Name = "Admin"; admin.Gender = "Male"; // !שדה חובה admin.user = user; admin.Type = "Admin"; DateTime date; bool parseResult = DateTime.TryParse("01.01.1980", out date); if (parseResult) { admin.BirthDate = date; DateTime now = DateTime.Today; int age = now.Year - admin.BirthDate.GetValueOrDefault().Year; if (now < admin.BirthDate.GetValueOrDefault().AddYears(age)) { age--; } admin.Age = age; } dal.users.Add(user); dal.admins.Add(admin); dal.SaveChanges(); return(true); } catch (Exception ex) { MessageBox.Show("" + ex.ToString()); } return(false); }
// function example to deleting user and student public static void deleteUser(int id) { try { // פעולת מחיקה DbContextDal dal = new DbContextDal(); // יצירת אובייקט משתמש כדי שניקלוט אליו משתמש קיים מהבסיס נתונים User user; Student std; // בגלל שסטודנט הוא מפתח זר של משתמש, כלומר אם קיים סטודנט זה רק בתנאי שקיים משתמש כזה // אז אם נמחוק את המשתמש קודם, אז הסטודנט לא יעמוד בתנאי הזה! // ולכן חייבים למחוק את הסטודנט לפני שמוחקים את המשתמש // ככה הגדרתי , שהת.ז. של הסטודנט הוא מפתח זר של משתמש // מציאת משתמש וסטודנט לפי מפתח ראשי user = dal.users.Find(id); std = dal.students.Find(id); // בדיקה אם מצאנו אובייקטים כלשהם במידה ולא, מסיימים את הפונקציה if (std == null || user == null) { return; } // הסרת האובייקט מרשימת האובייקטים שבבסיס נתונים dal.students.Remove(std); // קודם מסירים את הסטודנט dal.users.Remove(user); // ורק אז את המשתמש // שמירת מצב השינויים dal.SaveChanges(); } catch (Exception ex) { MessageBox.Show("" + ex.ToString()); } }
private void btn_update_Click(object sender, EventArgs e) { bool state = false; if (staffSelected != null) { state = setUpdateState(); if (state) { try { int id = System.Convert.ToInt32(txt_TB_ID.Text); userSelected = dal.users.Find(id); setUpdateState(); dal.SaveChanges(); btn_search_Click(sender, e); MessageBox.Show("The " + userSelected.permission + " detail updated!"); } catch (DbEntityValidationException ex) { //MessageBox.Show("Db Entity Validation Exception"); string str = "" + ex.Source + " : " + ex.GetType() + "\n-----------------------------------------------------------------------------------------------------\n" + "Message: " + ex.Message + "\n\nExplain & solution:\nThe problem is that you try to insert an object with data that does not fit the limitations of the data base to these object fields.\n\nThe following is a list of the incorrect features:\n"; foreach (var entityValidationErrors in ex.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { str += ("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage + "\n"); } } MessageBox.Show(str); } catch (Exception eu) { MessageBox.Show("Error: \n\n" + eu.ToString()); } } } }
private bool Add_Student(Student std, string pass = "") { try { string password = "******"; if (pass.Length > 0) { password = pass; } if (!SettingDatabase.Add_New_Student(std, password)) { MessageBox.Show("Some Error accure to create new user for this student"); return(false); } DbContextDal dal = new DbContextDal(); //User UserStudent = dal.users.Find(std.ID); User UserStudent = dal.users.Find(std.ID); if (UserStudent != null) { std.user = UserStudent; dal.students.Add(std); dal.SaveChanges(); MessageBox.Show("The Student " + std.ID + " Added!"); return(true); } else { MessageBox.Show("Error to add student, because the user of this student deosnt created!"); } } catch (DbEntityValidationException ex) { //MessageBox.Show("Db Entity Validation Exception"); string str = "" + ex.Source + " : " + ex.GetType() + "\n-----------------------------------------------------------------------------------------------------\n" + "Message: " + ex.Message + "\n\nExplain & solution:\nThe problem is that you try to insert an object with data that does not fit the limitations of the data base to these object fields.\n\nThe following is a list of the incorrect features:\n"; foreach (var entityValidationErrors in ex.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { str += ("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage + "\n"); } } MessageBox.Show(str); } catch (DbUnexpectedValidationException ex) { //MessageBox.Show("Db Unexpected Validation Exception"); string str = "" + ex.Source + " : " + ex.GetType() + "\n-----------------------------------------------------------------------------------------------------\n" + "Message: " + ex.Message; MessageBox.Show(str); } catch (DbUpdateException ex) { //MessageBox.Show("Db Update Exception"); string str = "" + ex.Source + " : " + ex.GetType() + "\n-----------------------------------------------------------------------------------------------------\n" + "Message: " + ex.Message + "\n\nExplain & solution:\nThe problem is that you are trying to insert an object that already exists in the system with the same key, or perform object updates with invalid variables in a database. You must enter differentiated data."; MessageBox.Show(str); } catch (InvalidOperationException ex) { //MessageBox.Show("Invalid Operation Exception"); string str = "" + ex.Source + " : " + ex.GetType() + "\n-----------------------------------------------------------------------------------------------------\n" + "Message: " + ex.Message + "\n\nExplain & solution:\nThe problem is that the database is formatted differently from what is currently in your class code. You must do 'add-migration update_i' to changes made during code writing in the class code, and then perform a 'update-database' in your PM."; MessageBox.Show(str); } catch (Exception ex) { //MessageBox.Show("Exception"); string str = "" + ex.Source + " : " + ex.GetType() + "\n-----------------------------------------------------------------------------------------------------\n" + "Message: " + ex.Message; MessageBox.Show(str); } return(false); }