public bool AddProfile(Model.Profile profile) { var returnValue = false; try { var pro = new Profile { Id = Guid.NewGuid(), Firstname = profile.Firstname, Middlename = profile.Middlename, Lastname = profile.Lastname, GenderId = profile.GenderId, StatusId = Guid.Parse(Constants.ACTIVESTATUS), CreatedBy = _username, CreatedDate = DateTime.Now }; _dbContext.Profile.Add(pro); var result = _dbContext.SaveChanges(); if (result == 1) { returnValue = true; } } catch (Exception ex) { throw ex; } return(returnValue); }
/// <summary> /// Delete the currently selected event /// </summary> private void DeleteSelectedEvent() { // Check that a room was selected if (SelectedEvent != null) { // Get the lesson that is going to be deleted Event selectedEvent = _schoolData.Events.Find(SelectedEvent.ID); // As this is a serious action, request a confirmation from the user bool confirmation = _messageBoxService.ShowMessage("האם אתה בטוח שברצונך למחוק את האירוע?", "מחיקת אירוע!", MessageType.ACCEPT_CANCEL_MESSAGE, MessagePurpose.INFORMATION); if (confirmation == true) { // Remove the lesson _schoolData.Events.Remove(selectedEvent); // Save and report changes _schoolData.SaveChanges(); SendMessageAboutEvent(selectedEvent, ActionOnEvent.Deleted); _messageBoxService.ShowMessage("האירוע נמחק בהצלחה!", "מחיקת אירוע!", MessageType.OK_MESSAGE, MessagePurpose.INFORMATION); _refreshDataCommand.Execute(null); } } else { _messageBoxService.ShowMessage("אנא בחר אירוע קודם כל.", "נכשל במחיקת אירוע", MessageType.OK_MESSAGE, MessagePurpose.ERROR); } }
/// <summary> /// Delete the currently selected lesson /// </summary> private void DeleteSelectedLesson() { // Check that a room was selected if (SelectedLesson == null) { _messageBoxService.ShowMessage("אנא בחר חדר קודם כל.", "נכשל במחיקת חדר", MessageType.OK_MESSAGE, MessagePurpose.ERROR); } else { // Get the lesson that is going to be deleted Lesson selectedLesson = _schoolData.Lessons.Find(SelectedLesson.ID); // As this is a serious action, request a confirmation from the user bool confirmation = _messageBoxService.ShowMessage("האם אתה בטוח שברצונך למחוק את השיעור?", "מחיקת שיעור!", MessageType.ACCEPT_CANCEL_MESSAGE, MessagePurpose.INFORMATION); if (confirmation == true) { // Remove the lesson _schoolData.Lessons.Remove(selectedLesson); // Save and report changes _schoolData.SaveChanges(); _messageBoxService.ShowMessage("השיעור נמחק בהצלחה!", "מחיקת שיעור!", MessageType.OK_MESSAGE, MessagePurpose.INFORMATION); _refreshDataCommand.Execute(null); } } }
public ActionResult AddArticle(ArticlesViewModel model) { bool isModelValid = CheckArticleModelValidity(model); if (!isModelValid) { model.IsUserAuthenticated = Session["UserCredentials"] != null; model.Articles = GetArticlesListFromDatabase(); return(View("Articles", model)); } // in case that session would expire if (((UserCredentials)Session["UserCredentials"]) != null) { var username = ((UserCredentials)Session["UserCredentials"]).Username; model.Article.RegisteredUser = _context.RegisteredUsers.First(user => user.Nickname == username); model.Article.PublicationDate = DateTime.Now; if (model.PhotosToInsertIDs != null) { var photosToInsert = _context.Photos.Where(photo => model.PhotosToInsertIDs.Contains(photo.PhotoId)).ToList(); photosToInsert.ToList().ForEach(p => model.Article.Photos.Add(p)); _context.SaveChanges(); } _context.Articles.Add(model.Article); _context.SaveChanges(); } return(RedirectToAction("Articles")); }
public ActionResult Create([Bind(Include = "ID,Name,Address,Email,Class")] Student student) { if (ModelState.IsValid) { db.Students.Add(student); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(student)); }
public ActionResult Create([Bind(Include = "ClassID,ClassName")] Class @class) { if (ModelState.IsValid) { db.Classes.Add(@class); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(@class)); }
public ActionResult Create([Bind(Include = "DepartmentId,Name,StartDate,Administrator")] Department department) { if (ModelState.IsValid) { db.Departments.Add(department); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(department)); }
public int Add(Class cls) { try { _dbContext.Class.Add(cls); return(_dbContext.SaveChanges()); } catch (Exception ex) { throw ex; } }
public int Add(Role roleData) { try { _dbContext.Role.Add(roleData); var returnValue = _dbContext.SaveChanges(); return(returnValue); } catch (Exception ex) { throw ex; } }
public int Add(User usr) { try { _dbContext.User.Add(usr); var result = _dbContext.SaveChanges(); return(result); } catch (Exception ex) { throw ex; } }
public ActionResult Create(tbl_Employees emp) { if (ModelState.IsValid) { dbContext.tbl_Employees.Add(emp); dbContext.SaveChanges(); return(View()); } else { return(View(emp)); } }
public void InsertDepartment(Department department) { try { department.DepartmentID = GenerateDepartmentID(); context.Departments.AddObject(department); context.SaveChanges(); } catch (Exception ex) { //Include catch blocks for specific exceptions first, //and handle or log the error as appropriate in each. //Include a generic catch block like this one last. throw ex; } }
/// <summary> /// Attempt to set the user password's /// </summary> /// <param name="parameter">The source window of the View that implement IHavePassword and IDialogWindow</param> private void SetPassword(object parameter) { SecureString password = (parameter as IHavePassword).SecurePassword; SecureString confirmationPassword = (parameter as IHavePassword).ConfirmationSecurePassword; // Reset error flags IsPasswordInvalid = false; IsConfirmationPasswordInvalid = false; // Check if the password is valid if (password.Length < Globals.MINIMUM_PASSWORD_LENGTH || password.Length > Globals.MAXIMUM_PASSWORD_LENGTH) { IsPasswordInvalid = true; } // Check if the confirmation password is the same as the actual password else if (password.Unsecure() != confirmationPassword.Unsecure()) { IsConfirmationPasswordInvalid = true; } else { // Password is valid. Save it and return. // Note that the password is saved in plain-text for convenience and simplification. In an actual product it would stay secured. _user.password = password.Unsecure(); _user.hasToChangePassword = false; _context.SaveChanges(); (parameter as IDialogWindow).CloseDialogWindow(true); } }
/// <summary> /// metodo que añade un curso nuevo /// </summary> /// <param name="c">curso a añadir</param> /// <returns>devulve el identificador del nuevo curso o -1 si no se puede añadir</returns> public static int Add(Course c) { try { if (c != null) { using (SchoolEntities db = new SchoolEntities()) { db.Course.Add(c); db.SaveChanges(); return(c.CourseID); } } else { return(-1); } } catch (SqlException sqlex) { return(-1); } catch (Exception ex) { return(-1); } }
private void BtnAddUser_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(TxtFirstName.Text) && !string.IsNullOrEmpty(TxtLastName.Text) && !string.IsNullOrEmpty(TxtPassword.Text) && (dateEnrollmentDate.Checked || dateHireDate.Checked) && comboBoxDisc.Text != null) { using (var db = new SchoolEntities()) { DateTime?dt = null; var hireDate = (dateHireDate.Enabled == true) ? dateHireDate.Value : dt; var enrollDate = (dateEnrollmentDate.Enabled == true) ? dateEnrollmentDate.Value : dt; var person = new Person() { LastName = TxtLastName.Text, FirstName = TxtFirstName.Text, HireDate = hireDate, EnrollmentDate = enrollDate, Discriminator = comboBoxDisc.SelectedItem.ToString(), Password = TxtPassword.Text }; db.Person.Add(person); db.SaveChanges(); dataGridView1.DataSource = db.Person.ToList(); dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true; dataGridView1.FirstDisplayedCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0]; } TxtFirstName.ResetText(); TxtLastName.ResetText(); TxtPassword.ResetText(); dateHireDate.ResetText(); dateEnrollmentDate.ResetText(); comboBoxDisc.SelectedItem = null; } else { MessageBox.Show("You havent entered every needed information.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
protected void AssignCourseButton_Click(object sender, EventArgs e) { using (var context = new SchoolEntities()) { var instructorID = Convert.ToInt32(InstructorsDropDownList.SelectedValue); var instructor = (from p in context.People where p.PersonID == instructorID select p).First(); var courseID = Convert.ToInt32(UnassignedCoursesDropDownList.SelectedValue); var course = (from c in context.Courses where c.CourseID == courseID select c).First(); instructor.Courses.Add(course); try { context.SaveChanges(); PopulateDropDownLists(); CourseAssignedLabel.Text = "Assignment successful."; } catch (Exception) { CourseAssignedLabel.Text = "Assignment unsuccessful."; //Add code to log the error. } CourseAssignedLabel.Visible = true; } }
protected void RemoveCourseButton_Click(object sender, EventArgs e) { using (var context = new SchoolEntities()) { var instructorID = Convert.ToInt32(InstructorsDropDownList.SelectedValue); var instructor = (from p in context.People where p.PersonID == instructorID select p).First(); var courseID = Convert.ToInt32(AssignedCoursesDropDownList.SelectedValue); var courses = instructor.Courses; var courseToRemove = new Course(); foreach (Course c in courses) { if (c.CourseID == courseID) { courseToRemove = c; break; } } try { courses.Remove(courseToRemove); context.SaveChanges(); PopulateDropDownLists(); CourseRemovedLabel.Text = "Removal successful."; } catch (Exception) { CourseRemovedLabel.Text = "Removal unsuccessful."; //Add code to log the error. } CourseRemovedLabel.Visible = true; } }
public ActionResult Create([Bind(Include = "st_id,fullname,gender,birth_date,phone")] Student student) { student.fullname = Remove_Successive_spaces(student.fullname); if (ModelState.IsValid) { int x; int.TryParse(Session["id"].ToString(), out x); student.father_id = x; db.Students.Add(student); db.SaveChanges(); return(RedirectToAction("StudentList")); } ViewBag.father_id = new SelectList(db.Fathers, "f_id", "username", student.father_id); return(View(student)); }
public IHttpActionResult Put(StudentViewModel student) { if (!ModelState.IsValid) { return(BadRequest("Not a valid model")); } using (var ctx = new SchoolEntities()) { var exitstingStudent = ctx.Students.Where(s => s.StudentId == student.Id).FirstOrDefault <Student>(); if (exitstingStudent != null) { exitstingStudent.FirstName = student.FirstName; exitstingStudent.LastName = student.LastName; ctx.SaveChanges(); } else { return(NotFound()); } } return(Ok()); }
//public Model.Response.ServiceResponseWithResultset<Model.Model.GenderModel> GetAll() //{ // try // { // var result = this._context.proc_Gender_GetAll().ToList(); // List<GenderModel> collection = new List<GenderModel>(); // foreach (var item in result) // { // collection.Add(new GenderModel // { // GenderDescription=item.genderDescription, // GenderId = item.genderId, // GenderLetter=item.genderLetter // }); // } // return new ServiceResponseWithResultset<GenderModel> // { // Response = Model.Enumerator.Enum.ServiceResponses.Success, // Reason = "OK", // Data = collection // }; // } // catch (Exception ex) // { // return new ServiceResponseWithResultset<GenderModel> // { // Response = Model.Enumerator.Enum.ServiceResponses.Failure, // Reason = "Error on GetAll method. " + ex.InnerException != null ? ex.InnerException.Message : ex.Message // }; // } //} //public IQueryable<Model.Model.GenderModel> FindBy(Model.Model.GenderModel entity) //{ // throw new NotImplementedException(); //} //public Model.Response.SaveResult Add(Model.Model.GenderModel entity) //{ // throw new NotImplementedException(); //} //public Model.Response.SaveResult Delete(Model.Model.GenderModel entity) //{ // throw new NotImplementedException(); //} //public Model.Response.SaveResult Edit(Model.Model.GenderModel entity) //{ // throw new NotImplementedException(); //} //public void Dispose() //{ // throw new NotImplementedException(); //} public SaveResult Add(List <PeriodGradeModel> periodGradeModelList) { try { foreach (var item in periodGradeModelList) { var periodGradeToAdd = new PeriodGrade { gradeId = item.GradeModel.GradeId, periodId = item.PeriodModel.PeriodId }; _context.Entry(periodGradeToAdd).State = System.Data.Entity.EntityState.Added; _context.SaveChanges(); } return(new SaveResult { Message = "Period Grades selected was created successfully!", Status = "OK" }); } catch (Exception ex) { return(new SaveResult { Message = "Error on PeriodGrade Add method. " + ex.InnerException != null ? ex.InnerException.Message : ex.Message, Status = "ERROR" }); } }
/// <summary> /// metodo que añade un curso nuevo /// </summary> /// <param name="c">curso a añadir</param> /// <returns>devulve el identificador del nuevo curso o -1 si no se puede añadir</returns> public static int Add(Course c) { try { if (c != null) { using(SchoolEntities db = new SchoolEntities()) { db.Course.Add(c); db.SaveChanges(); return c.CourseID; } } else { return -1; } } catch (SqlException sqlex) { return -1; } catch (Exception ex) { return -1; } }
private void SaveFileInLibrary(HttpPostedFileBase file) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath(pathToPhotosStorage), fileName); // Save file in server's storage and put link to it in database file.SaveAs(path); _context.Photos.Add( new Photo() { Link = Path.Combine(pathToPhotosStorage, fileName), // relative path FileName = fileName } ); _context.SaveChanges(); }
private void DataGridViewGrades_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Delete) { if (MessageBox.Show("Do you really want to delete this row?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { var selectedRow = DataGridViewGrades.SelectedRows[0].Cells[0].Value.ToString(); using (var db = new SchoolEntities()) { var query = from o in db.StudentGrade where o.EnrollmentID.ToString().Equals(selectedRow) select o; db.StudentGrade.Remove(query.First()); db.SaveChanges(); DataGridViewGrades.DataSource = db.StudentGrade.ToList(); DataGridViewGrades.FirstDisplayedCell = DataGridViewGrades.Rows[DataGridViewGrades.Rows.Count - 1].Cells[0]; } } } }
/// <summary> /// Reset data in preparation for a new year (deleting studentds, scores, messages, events...) /// </summary> private void PrepareNewYear() { if (HasRequiredPermissions) { // Ask for confirmation again as this is a dangerous action bool confirmationResult = _messageBoxService.ShowMessage("תהליך זה ימחק מידע על התלמידים הקיימים. האם להמשיך?", "Are you sure?", MessageType.ACCEPT_CANCEL_MESSAGE, MessagePurpose.INFORMATION); if (confirmationResult) { // Delete all yearly information (student users, events, scores, lessons...) SchoolEntities mySchool = new SchoolEntities(); // Delete students foreach (Person person in mySchool.Persons.Where(p => p.isStudent)) { person.User.isDisabled = true; mySchool.Persons.Remove(person); } mySchool.Students.RemoveRange(mySchool.Students); mySchool.Events.RemoveRange(mySchool.Events); mySchool.Messages.RemoveRange(mySchool.Messages); mySchool.Grades.RemoveRange(mySchool.Grades); mySchool.Lessons.RemoveRange(mySchool.Lessons); mySchool.SaveChanges(); _refreshDataCommand.Execute(null); _messageBoxService.ShowMessage("מידע עודכן!", "Saved Changes", MessageType.OK_MESSAGE, MessagePurpose.INFORMATION); } } }
private void dataGridView1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Delete) { if (MessageBox.Show("Do you really want to delete selected row?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { // removing by selecting courseid cell to delete // TODO: adding entry to onsite / online course and fixing courseinstructor table because its gonna crash when deleting base entries try { int val; int.TryParse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString(), out val); using (var db = new SchoolEntities()) { var query = from o in db.Course where o.CourseID.Equals(val) select o; var queryOnline = from o in db.OnlineCourse where o.CourseID.Equals(val) select o; var queryOnsite = from o in db.OnsiteCourse where o.CourseID.Equals(val) select o; var queryGrades = from o in db.StudentGrade where o.CourseID.Equals(val) select o; db.Course.Remove(query.First()); if (queryOnline.FirstOrDefault() != null) { db.OnlineCourse.Remove(queryOnline.First()); } if (queryOnsite.FirstOrDefault() != null) { db.OnsiteCourse.Remove(queryOnsite.First()); } if (queryGrades.FirstOrDefault() != null) { db.StudentGrade.RemoveRange(queryGrades.ToArray()); } db.SaveChanges(); dataGridView1.DataSource = db.Course.ToList(); } } catch (Exception ex) { MessageBox.Show("You cannot delete essential courses.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
private void BtnAdd_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(TxtName.Text) && !string.IsNullOrEmpty(TxtBudget.Text) && !string.IsNullOrEmpty(TxtName.Text) && comboBoxInstructors.Text != null) { using (var db = new SchoolEntities()) { // parsing budget if correct decimal budget = default; decimal.TryParse(TxtBudget.Text, out budget); if (budget.ToString() == "0") { MessageBox.Show("Invalid budget value.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // parsing deptid if correct int deptID = default; int.TryParse(TxtId.Text, out deptID); if (deptID.ToString() == "0") { MessageBox.Show("Invalid department ID value.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // getting dept admin id from name + surname var findAdmin = from o in db.Person where (o.FirstName + " " + o.LastName).Equals(comboBoxInstructors.Text) select o.PersonID; var dept = new Department() { Name = TxtName.Text, Budget = budget, DepartmentID = deptID, StartDate = dateTimeStart.Value, Administrator = findAdmin.First() }; TxtId.ResetText(); TxtBudget.ResetText(); TxtName.ResetText(); dateTimeStart.ResetText(); comboBoxInstructors.SelectedItem = null; db.Department.Add(dept); db.SaveChanges(); dataGridViewDepartments.DataSource = db.Department.ToList(); } } else { MessageBox.Show("Please enter missing information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// Delete the currently selected class /// </summary> private void DeleteSelectedClass() { // Check that a class was selected if (SelectedClass == null) { _messageBoxService.ShowMessage("אנא בחר כיתה קודם כל.", "נכשל במחיקת כיתה", MessageType.OK_MESSAGE, MessagePurpose.ERROR); } else { // Get the class that is going to be edited Class selectedClass = _schoolData.Classes.Find(SelectedClass.ID); // As this is a serious action, request a confirmation from the user bool confirmation = _messageBoxService.ShowMessage("האם אתה בטוח שברצונך למחוק את הכיתה " + selectedClass.className + "?", "מחיקת כיתה!", MessageType.ACCEPT_CANCEL_MESSAGE, MessagePurpose.INFORMATION); if (confirmation == true) { // Remove the class from any of its associations (events, students) _schoolData.Students.Where(student => student.classID == selectedClass.classID) .ToList().ForEach(student => student.classID = null); _schoolData.Events.Where(eventData => eventData.recipientClassID == selectedClass.classID) .ToList().ForEach(eventData => eventData.recipientClassID = null); // Lessons are meant only for a specific class and are meaningless after a class was removed - delete all lessons for this class var releventLessons = _schoolData.Lessons.Where(lesson => lesson.classID == selectedClass.classID); foreach (var lesson in releventLessons) { _schoolData.Lessons.Remove(lesson); } // Clear the previous class properties (as this class is removed) this._previousHomeroomTeacher = null; this._previousRoom = null; // Delete the class itself _schoolData.Classes.Remove(selectedClass); // Save and report changes _schoolData.SaveChanges(); _messageBoxService.ShowMessage("הכיתה " + selectedClass.className + " נמחקה בהצלחה!", "מחיקת כיתה!", MessageType.OK_MESSAGE, MessagePurpose.INFORMATION); _refreshDataCommand.Execute(null); } } }
private void BtnAddGrade_Click(object sender, EventArgs e) { if (ComboBoxCourse.Text != null && ComboBoxGrades.Text != null && ComboBoxStudents.Text != null) { using (var db = new SchoolEntities()) { var getCourse = from o in db.Course where o.Title.Equals(ComboBoxCourse.Text) select o.CourseID; int courseID = default; if (getCourse.Any()) { courseID = getCourse.First(); } var getStudent = from o in db.Person where (o.FirstName + " " + o.LastName).Equals(ComboBoxStudents.Text) select o.PersonID; int studentID = default; if (getStudent.Any()) { studentID = getStudent.First(); } decimal.TryParse(ComboBoxGrades.Text, out decimal studentGrade); var grade = new StudentGrade() { CourseID = courseID, StudentID = studentID, Grade = studentGrade }; db.StudentGrade.Add(grade); db.SaveChanges(); DataGridViewGrades.DataSource = db.StudentGrade.ToList(); ComboBoxCourse.SelectedItem = null; ComboBoxGrades.SelectedItem = null; ComboBoxStudents.SelectedItem = null; DataGridViewGrades.Rows[DataGridViewGrades.Rows.Count - 1].Selected = true; DataGridViewGrades.FirstDisplayedCell = DataGridViewGrades.Rows[DataGridViewGrades.Rows.Count - 1].Cells[0]; } } else { MessageBox.Show("Please provide all required information.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public void Remove(int id) { using (var contex = new SchoolEntities()) { var p = contex.Person.Find(id); contex.Person.Remove(p); contex.SaveChanges(); } }
public ActionResult Create(Teacher teacher) { using (SchoolEntities dbContext = new SchoolEntities()) { dbContext.Teachers.Add(teacher); dbContext.SaveChanges(); } return(RedirectToAction("Show")); }
public ActionResult Create(Student student) { using (SchoolEntities dbContext = new SchoolEntities()) { dbContext.Students.Add(student); dbContext.SaveChanges(); } return(View("Show")); }
public void ConcurrentUpdate_ClientWins() { using (new TransactionScope()) { using (var context1 = new SchoolEntities()) using (var context2 = new SchoolEntities()) { var p1 = context1.People.Find(1); var p2 = context2.People.Find(1); p1.FirstName = "UPDATE"; context1.SaveChanges(); try { p2.FirstName = "SOMETHING ELSE"; context2.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { var entry = ex.Entries.Single(); entry.OriginalValues.SetValues(entry.GetDatabaseValues()); context2.SaveChanges(); } Assert.AreEqual(p2.FirstName, "SOMETHING ELSE"); Assert.AreEqual(EntityState.Unchanged, context2.Entry(p2).State); context2.SaveChanges(); } using (var context = new SchoolEntities()) { Assert.AreEqual("SOMETHING ELSE", context.People.Find(1).FirstName); } } }
public void ConcurrencyCheck_ShouldBe_OnAllFields() { using (new TransactionScope()) using (var context1 = new SchoolEntities()) using (var context2 = new SchoolEntities()) { var p1 = context1.People.OfType<Instructor>().First(); var p2 = context2.People.Find(p1.PersonID) as Instructor; p1.Location = "Smalle Zijde 35"; context1.SaveChanges(); p2.Location = "Kruisboog 42"; context2.SaveChanges(); } }
public static void Main(string[] args) { SchoolEntities dbContext = new SchoolEntities(); //for (int i = 1; i <= 10; i++) //{ // Teacher teacher = new Teacher(); // teacher.Name = String.Format("Teacher #{0}", i); // dbContext.Teachers.Add(teacher); //} //dbContext.SaveChanges(); //Console.WriteLine("Teacher database setup all ready!"); for (int i = 1; i <= 100; i++) { Student student = new Student(); student.Name = String.Format("Student #{0}", i); int teacherId = i % 10; student.TeacherId = teacherId == 0 ? 10 : teacherId; dbContext.Students.Add(student); } dbContext.SaveChanges(); Console.WriteLine("Student database setup all ready!"); Console.ReadLine(); }
/// <summary> /// Metodo para añadir una nueva persona. Devuelve el id de la persona insertada. /// </summary> /// <param name="p">Objeto Person que contiene todos los datos de la persona que se quiere insertar excepto el id que se genera automatico al insertar. </param> /// <returns>Devuelve el id de la persona insertada si todo va bien y -1 si no se inserta</returns> public static int add(Person p) { try { using (SchoolEntities db = new SchoolEntities()) { db.Person.Add(p); db.SaveChanges(); } } catch (SqlException sqlex) { return -1; } catch (Exception ex) { return -1; } return p.PersonID; }
public void ConcurrentUpdate_DatabaseWins() { using (new TransactionScope()) { using (var context1 = new SchoolEntities()) using (var context2 = new SchoolEntities()) { var p1 = context1.People.Find(1); var p2 = context2.People.Find(1); p1.FirstName = "UPDATE"; context1.SaveChanges(); try { p2.FirstName = "SOMETHING ELSE"; context2.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { // Refreshes the tracked entities with new values from the database. ex.Entries.Single().Reload(); } Assert.AreEqual(p2.FirstName, "UPDATE"); Assert.AreEqual(EntityState.Unchanged, context2.Entry(p2).State); context2.SaveChanges(); } using (var context = new SchoolEntities()) { Assert.AreEqual("UPDATE", context.People.Find(1).FirstName); } } }
public void ConcurrentUpdate_ShouldNot_AffectRecord() { using (new TransactionScope()) { using (var context1 = new SchoolEntities()) using (var context2 = new SchoolEntities()) { var p1 = context1.People.Find(1); var p2 = context2.People.Find(1); p1.FirstName = "UPDATE"; context1.SaveChanges(); p2.FirstName = "SOMETHING ELSE"; context2.SaveChanges(); } using (var context = new SchoolEntities()) { Assert.AreEqual("UPDATE", context.People.Find(1).FirstName); } } }
/// <summary> /// metodo que elimina un curso dado su ID /// </summary> /// <param name="ID">identificador del curso a eliminar</param> /// <returns>verdadero o falso segun si tuvo exito o no</returns> public static bool Remove(int ID) { try { using (SchoolEntities db = new SchoolEntities()) { var consulta = from tabla in db.Course where tabla.CourseID == ID select tabla; Course curso = consulta.First(); db.Course.Remove(curso); db.SaveChanges(); return true; } } catch (SqlException sqlex) { return false; } catch (Exception ex) { return false; } }
public void DeleteFromContext() { using (var context = new SchoolEntities()) { context.People.RemoveRange(context.People.Where(p => p.FirstName == "Pietje")); context.SaveChanges(); } }
public void DetachedEntities_ShouldBe_AddedBeforeSaveChanges() { Person pietje = null; // Die scope werkt dus ook over contexten heen! using (new TransactionScope()) { using (var context = new SchoolEntities()) { // AsNoTracking zorgt ervoor dat de ChangeTracker buitenspel wordt gezet. pietje = context.People.AsNoTracking().First(p => p.PersonID == 33); } pietje.LastName = "AS NO TRACKING"; using (var context = new SchoolEntities()) { // Slecht idee, twee pietjes in de DB //context.People.Add(pietje); context.Entry(pietje).State = EntityState.Modified; context.SaveChanges(); } } }
public void ConcurrentUpdate_ClietnChooses() { using (new TransactionScope()) { using (var context1 = new SchoolEntities()) using (var context2 = new SchoolEntities()) { var p1 = context1.People.Find(1); var p2 = context2.People.Find(1); p1.FirstName = p1.LastName = "UPDATE"; context1.SaveChanges(); try { p2.FirstName = p2.LastName = "SOMETHING ELSE"; context2.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { var entry = ex.Entries.Single(); var current = entry.CurrentValues; var other = entry.GetDatabaseValues(); var resolved = other.Clone(); ClientChooses(current, other, resolved); entry.OriginalValues.SetValues(other); entry.CurrentValues.SetValues(resolved); context2.SaveChanges(); } Assert.AreEqual(p2.FirstName, "UPDATE"); Assert.AreEqual(p2.LastName, "SOMETHING ELSE"); Assert.AreEqual(EntityState.Unchanged, context2.Entry(p2).State); context2.SaveChanges(); } using (var context = new SchoolEntities()) { var p = context.People.Find(1); Assert.AreEqual("UPDATE", p.FirstName); Assert.AreEqual("SOMETHING ELSE", p.LastName); } } }
/// <summary> /// Metodo para eliminar la persona que se correpsonde con el id que se pasa por parametro. /// </summary> /// <param name="ID">id de la persona a eliminar de tipo int</param> /// <returns>devuelve true si se realizo correctamente y false si hubo algun problema</returns> public static bool remove(int ID) { try { using (SchoolEntities db = new SchoolEntities()) { var resultado = from e in db.Person where e.PersonID == ID select e; Person per = resultado.First(); db.Person.Remove(per); db.SaveChanges(); } } catch (SqlException sqlex) { throw sqlex; } catch (Exception ex) { throw ex; } return true; }
public void NotExistingInstructor_ShouldBe_Added() { // TransactionScope om onze test database niet te vervuilen. Handig! using (var ts = new TransactionScope()) using (var context = new SchoolEntities()) { var person = context .People .OfType<Student>() .FirstOrDefault(p => p.FirstName == "Pietje" && p.LastName == "Puk"); if (person == null) { person = new Student { FirstName = "Pietje", LastName = "Puk", EnrollmentDate = DateTime.Today }; context.People.Add(person); } else { person.LastName = "Update"; } try { context.SaveChanges(); } catch (DbEntityValidationException ex) { Console.WriteLine(string.Join(Environment.NewLine, ex.EntityValidationErrors.SelectMany(e => e.ValidationErrors.Select(f => f.ErrorMessage)))); Assert.Fail(); } } }