public ActionResult Edit(int id, Teacher teacher)
 {
     try
     {
         // TODO: Add update logic here
         if (ModelState.IsValid)
         {
             db.Entry(teacher).State = EntityState.Modified;
             db.SaveChanges();
             return(RedirectToAction("Index"));
         }
         return(View(teacher));
     }
     catch
     {
         return(View(teacher));
     }
 }
        public virtual T Update(T entity)
        {
            try
            {
                // Implement optimistic concurrency
                var entry = dbContext.Entry <T>(entity);
                entry.State = EntityState.Modified;

                return(entry.Entity);
                // return dbContext.Update<T>(entity).Entity;
            }
            catch (DbUpdateConcurrencyException e)
            {
                var errorMessage = ProcessException("UpdateApplianceDetailsAsync: db Update concurrency error: ",
                                                    e.Message,
                                                    e.InnerException,
                                                    ErrorType.Critical);
                throw new DataAccessException(errorMessage);
            }
            catch (DbUpdateException e)
            {
                var errorMessage = ProcessException("UpdateApplianceDetailsAsync: db update error: ",
                                                    e.Message,
                                                    e.InnerException,
                                                    ErrorType.Critical);
                throw new DataAccessException(errorMessage);
            }
            catch (InvalidOperationException e)
            {
                var errorMessage = ProcessException("UpdateApplianceDetailsAsync: db invalid operation error: ",
                                                    e.Message,
                                                    e.InnerException,
                                                    ErrorType.Critical);
                throw new DataAccessException(errorMessage);
            }
            catch (Exception e)
            {
                var errorMessage = ProcessException("UpdateApplianceDetailsAsync: db general error: ",
                                                    e.Message,
                                                    e.InnerException,
                                                    ErrorType.Critical);
                throw new DataAccessException(errorMessage);
            }
        }
Пример #3
0
        public IActionResult UpdatePerson(Person updatedPerson)
        {
            //checking to be sure our updatedPerson will fit into the database
            if (ModelState.IsValid)
            {
                //finding the person in the database from the Id of the person from the form
                //REMEMBER: the id of the updatedPerson is the SAME as the id of the datbasePerson
                Person databasePerson = _context.Person.Find(updatedPerson.Id);
                databasePerson.FirstName = updatedPerson.FirstName;
                databasePerson.LastName  = updatedPerson.LastName;
                databasePerson.Dob       = updatedPerson.Dob;

                _context.Entry(databasePerson).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

                _context.Update(databasePerson);
                _context.SaveChanges();
            }
            return(RedirectToAction("ListPeople"));
        }
 public ActionResult Edit(School school, HttpPostedFileBase upload)
 {
     school.Logo = db.School.Where(x => x.Id == school.Id).Select(y => y.Logo).FirstOrDefault();
     //save Display image
     if (upload != null && upload.ContentLength > 0)
     {
         using (var reader = new System.IO.BinaryReader(upload.InputStream))
         {
             school.Logo = reader.ReadBytes(upload.ContentLength);
         }
     }
     if (ModelState.IsValid)
     {
         db.Entry(school).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Edit", new { id = school.Id }));
     }
     return(View(school));
 }
Пример #5
0
 public ActionResult Edit(Employee employee, HttpPostedFileBase EmployeeImage)
 {
     employee.Image = db.Employee.Where(x => x.Id == employee.Id).Select(y => y.Image).FirstOrDefault();
     //save Display image
     if (EmployeeImage != null && EmployeeImage.ContentLength > 0)
     {
         using (var reader = new System.IO.BinaryReader(EmployeeImage.InputStream))
         {
             employee.Image = reader.ReadBytes(EmployeeImage.ContentLength);
         }
     }
     if (ModelState.IsValid)
     {
         db.Entry(employee).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(employee));
 }
 public ActionResult Edit(JobInfo jobInfo, HttpPostedFileBase AppointmentImage)
 {
     if (ModelState.IsValid)
     {
         if (AppointmentImage != null && AppointmentImage.ContentLength > 0)
         {
             using (var reader = new System.IO.BinaryReader(AppointmentImage.InputStream))
             {
                 jobInfo.Appointment = reader.ReadBytes(AppointmentImage.ContentLength);
             }
         }
         db.Entry(jobInfo).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.DesignationId = new SelectList(db.Designation, "Id", "Name", jobInfo.DesignationId);
     ViewBag.EmployeeId    = new SelectList(db.Employee, "Id", "Name", jobInfo.EmployeeId);
     return(View(jobInfo));
 }
 public ActionResult Edit(Admission admission, HttpPostedFileBase Document)
 {
     if (ModelState.IsValid)
     {
         if (Document != null && Document.ContentLength > 0)
         {
             using (var reader = new System.IO.BinaryReader(Document.InputStream))
             {
                 admission.PreviousSchoolDocument = reader.ReadBytes(Document.ContentLength);
             }
         }
         db.Entry(admission).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.StudentClassId = new SelectList(db.StudentClass, "Id", "Name", admission.StudentClassId);
     ViewBag.StudentId      = new SelectList(db.Student, "Id", "Name", admission.StudentId);
     ViewBag.GroupId        = new SelectList(db.Group, "Id", "Name", admission.GroupId);
     return(View(admission));
 }
        public ActionResult Edit(ExamMark examMark)
        {
            if (ModelState.IsValid)
            {
                db.Entry(examMark).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            var studentClass = db.StudentClass.Select(c => new
            {
                Id   = c.Id,
                Name = c.ClassName.Name + " || " + c.Shift.Name + " ||" + c.Section.Name
            }).OrderBy(o => o.Name).ToList();

            ViewBag.SessionId      = new SelectList(db.Session, "Id", "Name");
            ViewBag.CourseId       = new SelectList(db.Course, "Id", "Name");
            ViewBag.StudentClassId = new SelectList(studentClass, "Id", "Name");
            ViewBag.AssignRollId   = new SelectList(db.AssignRoll, "Id", "Roll");
            return(View(examMark));
        }
Пример #9
0
        public ActionResult Edit([Bind(Include = "DepartmentId,DepartmentName,Capacity")] Department department)



        {
            SchoolSystem.DbModels.Model.Department dept = new SchoolSystem.DbModels.Model.Department()
            {
                DepartmentId   = department.DepartmentId,
                DepartmentName = department.DepartmentName,
                Capacity       = department.Capacity
            };

            if (ModelState.IsValid)
            {
                db.Entry(dept).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(department));
        }
        public ActionResult Edit([Bind(Include = "TeacherId,LastName,FirstName,HireDate,Major,Department,Course")] Instructor instructor)
        {
            SchoolSystem.DbModels.Model.Instructor instructorToEdit = new SchoolSystem.DbModels.Model.Instructor
            {
                InstructorId = instructor.TeacherId,
                FirstName    = instructor.FirstName,
                LastName     = instructor.LastName,
                Major        = instructor.Major,
                HireDate     = instructor.HireDate,
                DepartmentId = int.Parse(instructor.Department),
                CourseId     = int.Parse(instructor.Course)
            };

            if (ModelState.IsValid)
            {
                db.Entry(instructorToEdit).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(instructor));
        }
Пример #11
0
        public ActionResult Edit([Bind(/*Exclude = "Title",*/ Include = "CourseId,Title,Credit,Price")] SchoolSystem.DbModels.Model.Course course)
        {
            //TODO: bug code was added to handle title while editing

            /*string currentTitle=String.Empty;
             * foreach (var v in db.courses.Where(x => x.CourseId == course.CourseId)){currentTitle = v.Title;}
             * var c= new Course(){
             * CourseId = course.CourseId,
             * Title= currentTitle,
             * Credit = course.Credit,
             * Price = course.Price
             * };*/
            if (ModelState.IsValid)
            {
                db.Entry(course).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", "Please check fields for errors");
            return(View(course));
        }
Пример #12
0
        public async Task <IActionResult> PutStudent([FromRoute] Guid id, [FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != student.Id)
            {
                return(BadRequest());
            }

            if (_dbContext.Classes.Find(student.ClassId) == null)
            {
                return(BadRequest("Cannot find parent Class by id."));
            }

            _dbContext.Entry(student).State = EntityState.Modified;

            try
            {
                await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                // assume that exception occurred when unique constraint failed with codes: 2601 for MSSQL and 19 for SQLite
                if (ex.InnerException.Message.ToLowerInvariant().Contains("unique"))
                {
                    return(new ContentResult
                    {
                        StatusCode = StatusCodes.Status409Conflict,
                        Content = "Student with the same surname already exists."
                    });
                }
                throw;
            }

            return(NoContent());
        }
        public async Task <bool> UpdateAsync(Course course)
        {
            _context.Entry(course).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await CourseExistsAsync(course.Id))
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }

            return(true);
        }
Пример #14
0
        public async Task <bool> UpdateAsync(Technology technology)
        {
            _context.Entry(technology).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await TechnologyExistsAsync(technology.Id))
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }

            return(true);
        }
        public async Task <bool> UpdateStudent(long id, Student student)
        {
            _context.Entry(student).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();

                return(true);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }
        }
Пример #16
0
        public void EditClass(int ClassId, string className, string location, string teacherName)
        {
            try
            {
                var schoolClass = GetClass(ClassId);

                if (schoolClass == null)
                {
                    return;
                }

                schoolClass.Name        = className;
                schoolClass.Location    = location;
                schoolClass.TeacherName = teacherName;

                _dbContext.Entry(schoolClass).State = EntityState.Modified;
                _dbContext.SaveChanges();
            }
            catch (Exception e)
            {
                DomainEventSource.Log.Failure(e.Message);
            }
        }
Пример #17
0
        public void EditStudent(int StudentId, string studentName, int studentAge, double studentGPA)
        {
            try
            {
                var student = GetStudent(StudentId);

                if (student == null)
                {
                    return;
                }

                student.Name = studentName;
                student.Age  = studentAge;
                student.GPA  = studentGPA;

                _dbContext.Entry(student).State = EntityState.Modified;
                _dbContext.SaveChanges();
            }
            catch (Exception e)
            {
                DomainEventSource.Log.Failure(e.Message);
            }
        }
Пример #18
0
 public async Task <IActionResult> PutStudent(string id, Student student)
 {
     if (id != student.StudentId)
     {
         return(BadRequest());
     }
     _context.Entry(student).State = EntityState.Modified;
     try
     {
         await _context.SaveChangesAsync();
     }
     catch (DbUpdateConcurrencyException)
     {
         if (!StudentExists(id))
         {
             return(Conflict());
         }
         else
         {
             throw;
         }
     }
     return(NoContent());
 }
Пример #19
0
 public void Update(T obj)
 {
     table.Attach(obj);
     _context.Entry(obj).State = EntityState.Modified;
 }
Пример #20
0
 public virtual bool Edit(TEntity entity)
 {
     Db.Entry(entity).State = EntityState.Modified;
     return(true);
 }
Пример #21
0
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var department = await _context.Departments.Include(a => a.Administrator).SingleOrDefaultAsync(a => a.Id == id);

            if (department == null)
            {
                //ModelState.AddModelError("","该部门信息已被其他人删除!");
                //return NotFound();
                var deletedDepartment = new Department();

                await TryUpdateModelAsync(deletedDepartment);

                ModelState.AddModelError(string.Empty, "无法进行数据的修改。该部门信息已经被其他人所删除!");
                ViewBag.InstructorId =
                    new SelectList(_context.Instructors, "Id", "RealName", deletedDepartment.InstructorId);
                return(View(deletedDepartment));
            }

            _context.Entry(department).Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(department, "", a => a.Name, a => a.StartDate, a => a.Budget, a => a.InstructorId))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException ex)//rowVersion不一致,说明被改
                {
                    var exceptionEntity = ex.Entries.Single();
                    var clientValue     = (Department)exceptionEntity.Entity;
                    var databaseEntity  = exceptionEntity.GetDatabaseValues();
                    if (databaseEntity == null)
                    {
                        ModelState.AddModelError(string.Empty, "无法进行数据的修改。该部门信息已经被其他人所删除!");
                    }
                    else
                    {
                        var databaseValues = (Department)databaseEntity.ToObject();
                        if (databaseValues.Name != clientValue.Name)
                        {
                            ModelState.AddModelError("Name", $"当前值:{databaseValues.Name}");
                        }
                        if (databaseValues.Budget != clientValue.Budget)
                        {
                            ModelState.AddModelError("Budget", $"当前值:{databaseValues.Budget}");
                        }
                        if (databaseValues.StartDate != clientValue.StartDate)
                        {
                            ModelState.AddModelError("StartDate", $"当前值:{databaseValues.StartDate}");
                        }
                        if (databaseValues.InstructorId != clientValue.InstructorId)
                        {
                            var instructorEntity =
                                await _context.Instructors.SingleOrDefaultAsync(
                                    a => a.Id == databaseValues.InstructorId);

                            ModelState.AddModelError("InstructorId", $"当前值:{instructorEntity?.RealName}");
                        }

                        ModelState.AddModelError("", "你正在编辑的记录已经被其他用户所修改,编辑操作已经被取消,数据库当前的值已经显示在页面上。请再次点击保存。否则请返回列表。");

                        department.RowVersion = databaseValues.RowVersion;
                        ModelState.Remove("RowVersion");
                    }
                }
            }
            ViewData["InstructorId"] = new SelectList(_context.Instructors, "Id", "RealName", department.InstructorId);
            return(View(department));
            //if (id != department.Id)
            //{
            //    return NotFound();
            //}

            //if (ModelState.IsValid)
            //{
            //    try
            //    {
            //        _context.Update(department);
            //        await _context.SaveChangesAsync();
            //    }
            //    catch (DbUpdateConcurrencyException)
            //    {
            //        if (!DepartmentExists(department.Id))
            //        {
            //            return NotFound();
            //        }
            //        else
            //        {
            //            throw;
            //        }
            //    }
            //    return RedirectToAction(nameof(Index));
            //}
        }
Пример #22
0
 public void AddedStateTest()
 {
     _schoolDbContextSut.Students.Add(_studentEntity);
     Assert.Equal(EntityState.Added, _schoolDbContextSut.Entry(_studentEntity).State);
 }
        public async Task <IActionResult> Edit(int?id, byte[] rowVersion)
        {
            if (id == null)
            {
                return(NotFound());
            }
            var department = await _context.Departments.Include(a => a.Administrator).SingleOrDefaultAsync(a => a.Id == id);

            if (department == null)
            {
                var deletedDepartment = new Department();

                await TryUpdateModelAsync(deletedDepartment);

                ModelState.AddModelError(string.Empty, "无法进行数据修改,该部门信息已经被其他人删除");
                ViewBag.InstructorId = new SelectList(_context.Instructors, "Id", "RealName", deletedDepartment.InstructorId);
                return(View(deletedDepartment));
            }
            _context.Entry(department).Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(department, "", a => a.Name, a => a.StartDate, a => a.Budget, a => a.InstructorId))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException ex) // 这里是主要内容
                {
                    var exceptionEntity = ex.Entries.Single();
                    var clientValue     = (Department)exceptionEntity.Entity;

                    var databaseEntity = exceptionEntity.GetDatabaseValues();

                    if (databaseEntity == null)
                    {
                        ModelState.AddModelError(string.Empty, "无法进行数据修改,该部门信息已经被其他人删除");
                    }
                    else
                    {
                        var databaseValues = (Department)databaseEntity.ToObject();
                        if (databaseValues.Name != clientValue.Name)
                        {
                            ModelState.AddModelError("Name", $"当前值错误:{databaseValues.Name}");
                        }
                        if (databaseValues.Budget != clientValue.Budget)
                        {
                            ModelState.AddModelError("Budget", $"当前值错误:{databaseValues.Budget}");
                        }
                        if (databaseValues.StartDate != clientValue.StartDate)
                        {
                            ModelState.AddModelError("StartDate", $"当前值错误:{databaseValues.StartDate}");
                        }
                        if (databaseValues.InstructorId != clientValue.InstructorId)
                        {
                            var instructorEntity = await _context.Instructors.SingleOrDefaultAsync(a => a.Id == databaseValues.InstructorId);

                            ModelState.AddModelError("InstructorId", $"当前值错误:{instructorEntity?.RealName}");
                        }

                        ModelState.AddModelError("", "你正在编辑得记录已经被其他用户修改,编辑操作已经被取消,数据库当前得值已经显示页面上,请再次点击保存.否者返回列表");

                        department.RowVersion = databaseValues.RowVersion;

                        ModelState.Remove("RowVersion");
                    }
                }
            }
            ViewBag.InstructorId = new SelectList(_context.Instructors, "Id", "RealName", department.InstructorId);
            return(View(department));
        }
Пример #24
0
        public async Task <int> UpdateDepartmentAndSaveAsync(DepartmentAddEditDto dto, byte[] rowVersion)
        {
            var result = 0;

            try
            {
                var departmentToUpdate = await _context.Departments
                                         .FirstOrDefaultAsync(m => m.DepartmentId == dto.DepartmentId);

                if (departmentToUpdate == null)
                {
                    var errMsg = $"Record does not exist or has been deleted for DepartmentId={dto.DepartmentId}";
                    _logger.LogError("", errMsg);
                    throw new GeneralException(errMsg);
                }

                _context.Entry(departmentToUpdate).Property("RowVersion").OriginalValue = rowVersion;

                departmentToUpdate.Budget       = dto.Budget;
                departmentToUpdate.InstructorId = dto.InstructorId;
                departmentToUpdate.Name         = dto.Name;
                departmentToUpdate.StartDate    = dto.StartDate;

                // Comment out this line to enable updating only the fields with changed values
                //_context.Departments.Update(courseInDb);

                result = await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                var exceptionEntry = ex.Entries.Single();
                var userValues     = (Department)exceptionEntry.Entity;
                var dbEntry        = exceptionEntry.GetDatabaseValues();
                var errMsg         = "";
                if (dbEntry == null)
                {
                    errMsg = "Unable to save changes. The department was deleted by another user.";
                    throw new GeneralException(errMsg);
                }
                else
                {
                    var dbValues = (Department)dbEntry.ToObject();

                    if (dbValues.Name != userValues.Name)
                    {
                        errMsg += $"<li>Conflict field \"Name\": New value is \"{dbValues.Name}\"</li>";
                    }
                    if (dbValues.Budget != userValues.Budget)
                    {
                        errMsg += $"<li>Conflict field \"Budget\": New value is \"{dbValues.Budget:c}\"</li>";
                    }
                    if (dbValues.StartDate != userValues.StartDate)
                    {
                        errMsg += $"<li>Conflict field \"StartDate\": New value is \"{dbValues.StartDate:d}\"</li>";
                    }
                    if (dbValues.InstructorId != userValues.InstructorId)
                    {
                        Instructor dbInstructor = await _context.Instructors
                                                  .FirstOrDefaultAsync(i => i.InstructorId == dbValues.InstructorId);

                        errMsg += $"<li>Conflict field \"Administrator\": New value is \"{dbInstructor?.FullName}\"</li>";
                    }

                    errMsg = "The record you attempted to edit "
                             + "was modified by another user after you got the original value."
                             + "<br><br>The edit operation was canceled and the new values in the database displayed as below:"
                             + "<ul>" + errMsg + "</ul>"
                             + "<br>If you still intend to edit this record, click "
                             + "the \"Save\" button again. Otherwise click the \"Back to List\".";

                    dto.RowVersion = (byte[])dbValues.RowVersion;

                    throw new GeneralException(errMsg);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Failed to update Department: {dto}");
                throw ex;
            }

            return(result);
        }
Пример #25
0
 public void AddedStateTest()
 {
     schoolDbContextSUT.Students.Add(studentEntity);
     Assert.Equal(EntityState.Added, schoolDbContextSUT.Entry(studentEntity).State);
 }