public ValidationResultDto ValidateBeforeCreate(LopForCreateDto lop) { var totalTenLop = _context.DanhSachLop.Count(x => x.TenLop.ToLower().Contains(lop.TenLop.ToLower())); var totalTenVietTat = _context.DanhSachLop.Count(x => x.TenVietTat.ToLower().Contains(lop.TenVietTat.ToLower())); IDictionary <string, string[]> Errors = new Dictionary <string, string[]>(); if (totalTenLop >= 1 || totalTenVietTat >= 1) { if (totalTenLop >= 1) { Errors.Add("tenLop", new string[] { "tenLop is duplicated!" }); } if (totalTenVietTat >= 1) { Errors.Add("tenVietTat", new string[] { "tenVietTat is duplicated!" }); } return(new ValidationResultDto { IsValid = false, Errors = Errors }); } else { return(new ValidationResultDto { IsValid = true }); } }
public async Task <Lop> Create(LopForCreateDto lop) { var danhSachLop = await _context.DanhSachLop.OrderByDescending(x => x.MaLop).FirstOrDefaultAsync(); var maLop = 0; if (danhSachLop == null) { maLop = 0; } else { maLop = danhSachLop.MaLop + 1; } var newLop = new Lop { MaLop = maLop, TenLop = lop.TenLop, TenVietTat = lop.TenVietTat, MaKhoa = lop.MaKhoa, HeDaoTao = lop.HeDaoTao, MaKhoaDaoTao = lop.MaKhoaDaoTao, ThoiGianTao = DateTime.Now, ThoiGianCapNhat = DateTime.Now, TrangThai = 1 }; await _context.DanhSachLop.AddAsync(newLop); await _context.SaveChangesAsync(); return(newLop); }
public async Task <IActionResult> Create(LopForCreateDto lop) { try { var validationResult = _repo.ValidateBeforeCreate(lop); if (validationResult.IsValid) { var result = await _repo.Create(lop); return(StatusCode(201, new SuccessResponseDto { Message = "Tạo " + _entityName + " mới thành công!", Result = new SuccessResponseResultWithSingleDataDto { Data = result } })); } else { return(StatusCode(500, new FailedResponseDto { Message = "Tạo " + _entityName + " mới thất bại!", Result = new FailedResponseResultDto { Errors = validationResult.Errors } })); } } catch (Exception e) { return(StatusCode(500, new FailedResponseDto { Message = "Tạo " + _entityName + " mới thất bại!", Result = new FailedResponseResultDto { Errors = e } })); } }