Exemple #1
0
        public async Task OnGetAsync(int?id, int?courseID)
        {
            Instructor             = new InstructorIndexData();
            Instructor.Instructors = await _context.Instructors
                                     .Include(i => i.OfficeAssignment)
                                     .Include(i => i.CourseAssignments)
                                     .ThenInclude(i => i.Course)
                                     .ThenInclude(i => i.Department)
                                     //.Include(i => i.CourseAssignments)
                                     //	.ThenInclude(i => i.Course)
                                     //		.ThenInclude(i => i.Enrollments)
                                     //			.ThenInclude(i => i.Student)
                                     // .AsNoTracking()
                                     .OrderBy(i => i.LastName)
                                     .ToListAsync();

            if (id != null)
            {
                InstructorID = id.Value;
                Instructor instructor = Instructor.Instructors.Single(
                    i => i.ID == id.Value);
                Instructor.Courses = instructor.CourseAssignments.Select(s => s.Course);
            }

            if (courseID != null)
            {
                CourseID = courseID.Value;
                var selectedCourse = Instructor.Courses.Where(x => x.CourseID == courseID).Single();
                await _context.Entry(selectedCourse).Collection(x => x.Enrollments).LoadAsync();

                foreach (Enrollment enrollment in selectedCourse.Enrollments)
                {
                    await _context.Entry(enrollment).Reference(x => x.Student).LoadAsync();
                }
                Instructor.Enrollments = selectedCourse.Enrollments;
            }
        }
Exemple #2
0
        public async Task <IActionResult> OnPostAsync(int id)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var departmentToUpdate = await _context.Departments
                                     .Include(i => i.Administrator)
                                     .FirstOrDefaultAsync(m => m.DepartmentID == id);

            // null means Department was deleted by another user.
            if (departmentToUpdate == null)
            {
                return(await HandleDeletedDepartment());
            }

            // Update the RowVersion to the value when this entity was
            // fetched. If the entity has been updated after it was
            // fetched, RowVersion won't match the DB RowVersion and
            // a DbUpdateConcurrencyException is thrown.
            // A second postback will make them match, unless a new
            // concurrency issue happens.
            _context.Entry(departmentToUpdate)
            .Property("RowVersion").OriginalValue = Department.RowVersion;
            #endregion

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "Department",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                #region snippet_try
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToPage("./Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Department)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty, "Unable to save. " +
                                                 "The department was deleted by another user.");
                        return(Page());
                    }

                    var dbValues = (Department)databaseEntry.ToObject();
                    await setDbErrorMessage(dbValues, clientValues, _context);

                    // Save the current RowVersion so next postback
                    // matches unless an new concurrency issue happens.
                    Department.RowVersion = (byte[])dbValues.RowVersion;
                    // Must clear the model error for the next postback.
                    ModelState.Remove("Department.RowVersion");
                }
                #endregion
            }

            InstructorNameSL = new SelectList(_context.Instructors,
                                              "ID", "FullName", departmentToUpdate.InstructorID);

            return(Page());
        }
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync(int id)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            // Fetch current department from DB.
            // ConcurrencyToken may have changed.
            var departmentToUpdate = await _context.Departments
                                     .Include(i => i.Administrator)
                                     .FirstOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentToUpdate == null)
            {
                return(HandleDeletedDepartment());
            }

            // Set ConcurrencyToken to value read in OnGetAsync
            _context.Entry(departmentToUpdate).Property(
                d => d.ConcurrencyToken).OriginalValue = Department.ConcurrencyToken;

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "Department",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToPage("./Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Department)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty, "Unable to save. " +
                                                 "The department was deleted by another user.");
                        return(Page());
                    }

                    var dbValues = (Department)databaseEntry.ToObject();
                    await setDbErrorMessage(dbValues, clientValues, _context);

                    // Save the current ConcurrencyToken so next postback
                    // matches unless an new concurrency issue happens.
                    Department.ConcurrencyToken = (byte[])dbValues.ConcurrencyToken;
                    // Clear the model error for the next postback.
                    ModelState.Remove($"{nameof(Department)}.{nameof(Department.ConcurrencyToken)}");
                }
            }

            InstructorNameSL = new SelectList(_context.Instructors,
                                              "ID", "FullName", departmentToUpdate.InstructorID);

            return(Page());
        }
Exemple #4
0
 public async Task UpdateAsync(T entity)
 {
     _dbContext.Entry(entity).State = EntityState.Modified;
     await _dbContext.SaveChangesAsync();
 }
Exemple #5
0
 public Task Update(T entity)
 {
     // In case AsNoTracking is used
     Context.Entry(entity).State = EntityState.Modified;
     return(Context.SaveChangesAsync());
 }
Exemple #6
0
        public async Task <IActionResult> OnPostAsync(int?id,
                                                      [ModelBinder(Name = "Department.RowVersion")] byte[] rowVersion)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var departmentToUpdate = await _context.Departments
                                     .Include(i => i.Administrator)
                                     .FirstOrDefaultAsync(m => m.DepartmentID == id);

            // null means Department was deleted by another user.
            if (departmentToUpdate == null)
            {
                Department deletedDepartment = new Department();
                // Fetch the posted data so we can display it with the error message.
                await TryUpdateModelAsync(deletedDepartment);

                CopyDepartment(deletedDepartment);
                ModelState.AddModelError(string.Empty,
                                         "Unable to save. The department was deleted by another user.");
                ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName",
                                                          Department.InstructorID);
                return(Page());
            }

            var rowVersionParmStr = rowVersion[7];
            var rowVersionOrgStr  = ((byte[])(_context.Entry(departmentToUpdate)
                                              .Property("RowVersion")).OriginalValue)[7];

            // OriginalValue is the current value in the DB when this entity
            // was fetched. OriginalValue == rowVersion unless there is a
            // concurrency difference. rowVersion is the value when this record
            // was fetched by OnGetAsync. Set .OriginalValue = rowVersion to detect a
            // concurrency problem. A second postback will make them match.
            _context.Entry(departmentToUpdate)
            .Property("RowVersion").OriginalValue = rowVersion;

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "Department",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToPage("./Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Department)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Unable to save changes. The department was deleted " +
                                                 "by another user.");
                        return(Page());
                    }

                    var dbValues = (Department)databaseEntry.ToObject();
                    await setDbErrorMessage(dbValues, clientValues, _context);

                    var dbRowVers = ((byte[])dbValues.RowVersion)[7];

                    // Save the current RowVersion  so
                    // it can be posted back to this method in a hidden field.
                    Department.RowVersion = (byte[])dbValues.RowVersion;
                    ModelState.Remove("RowVersion");
                }
            }

            ViewData["InstructorID"] = new SelectList(_context.Instructors, "ID", "FullName", departmentToUpdate.InstructorID);
            return(Page());
        }
Exemple #7
0
        public async Task <IActionResult> OnPostAsync(int id)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var departmentToUpdate = await _context.Departments
                                     .Include(i => i.Administrator)
                                     .FirstOrDefaultAsync(m => m.DepartmentID == id);

            if (departmentToUpdate == null)
            {
                return(HandleDeletedDepartment());
            }

            _context.Entry(departmentToUpdate)
            .Property("RowVersion").OriginalValue = Department.RowVersion;     //отслеживание изменений

            if (await TryUpdateModelAsync <Department>(
                    departmentToUpdate,
                    "Department",
                    s => s.Name, s => s.StartDate, s => s.Budget, s => s.InstructorID))
            {
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToPage("./Index"));
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    var exceptionEntry = ex.Entries.Single();
                    var clientValues   = (Department)exceptionEntry.Entity;
                    var databaseEntry  = exceptionEntry.GetDatabaseValues();
                    if (databaseEntry == null)
                    {
                        ModelState.AddModelError(string.Empty, "Сохранение отклонено. " +
                                                 "Данные изменены другим пользователем.");
                        return(Page());
                    }

                    var dbValues = (Department)databaseEntry.ToObject();
                    await setDbErrorMessage(dbValues, clientValues, _context);

                    // Save the current RowVersion so next postback
                    // matches unless an new concurrency issue happens.
                    Department.RowVersion = (byte[])dbValues.RowVersion;

                    /* код задает для RowVersion новое значение,
                     * полученное из базы данных. Когда пользователь в следующий раз нажимает кнопку Save (Сохранить),
                     * перехватываются только те ошибки параллелизма,
                     * возникшие с момента последнего отображения страницы "Edit" (Редактирование).
                     */
                    // Clear the model error for the next postback.
                    ModelState.Remove("Department.RowVersion");

                    /* Оператор ModelState.Remove является обязательным, так как ModelState имеет старое значение RowVersion.
                     * На странице Razor значение ModelState для поля имеет приоритет над значениями свойств модели,
                     * если они присутствуют вместе.
                     */
                }
            }

            InstructorNameSL = new SelectList(_context.Instructors,
                                              "ID", "FullName", departmentToUpdate.InstructorID);

            return(Page());
        }