public ValidationResultDto ValidateBeforeUpdate(int id, KhoaForUpdateDto khoa) { var totalTenKhoa = _context.DanhSachKhoa.Count(x => x.MaKhoa != id && x.TenKhoa.ToLower() == khoa.TenKhoa.ToLower()); var totalTenVietTat = _context.DanhSachKhoa.Count(x => x.MaKhoa != id && x.TenVietTat.ToLower() == khoa.TenVietTat.ToLower()); IDictionary <string, string[]> Errors = new Dictionary <string, string[]>(); if (totalTenKhoa > 0 || totalTenVietTat > 0) { if (totalTenKhoa > 0) { Errors.Add("tenKhoa", new string[] { "tenKhoa is duplicated!" }); } if (totalTenVietTat > 0) { Errors.Add("tenVietTat", new string[] { "tenVietTat is duplicated!" }); } return(new ValidationResultDto { IsValid = false, Errors = Errors }); } else { return(new ValidationResultDto { IsValid = true }); } }
public async Task <Khoa> UpdateById(int id, KhoaForUpdateDto khoa) { var oldRecord = await _context.DanhSachKhoa.AsNoTracking().FirstOrDefaultAsync(x => x.MaKhoa == id); var khoaToUpdate = new Khoa { MaKhoa = id, TenKhoa = khoa.TenKhoa, TenVietTat = khoa.TenVietTat, ThoiGianTao = oldRecord.ThoiGianTao, ThoiGianCapNhat = DateTime.Now, TrangThai = khoa.TrangThai }; _context.DanhSachKhoa.Update(khoaToUpdate); await _context.SaveChangesAsync(); return(khoaToUpdate); }
public async Task <IActionResult> UpdateById(int id, KhoaForUpdateDto khoa) { try { var validationResult = _repo.ValidateBeforeUpdate(id, khoa); if (validationResult.IsValid) { var result = await _repo.UpdateById(id, khoa); return(StatusCode(200, new SuccessResponseDto { Message = "Cập nhật " + _entityName + " thành công!", Result = new SuccessResponseResultWithSingleDataDto { Data = result } })); } else { return(StatusCode(500, new FailedResponseDto { Message = "Cập nhật " + _entityName + " mới thất bại!", Result = new FailedResponseResultDto { Errors = validationResult.Errors } })); } } catch (Exception e) { return(StatusCode(500, new FailedResponseDto { Message = "Cập nhật " + _entityName + " thất bại!", Result = new FailedResponseResultDto { Errors = e } })); } }