public ValidationResultDto ValidateBeforeCreate(SinhVienForCreateDto sinhVien) { var totalEmail = _context.DanhSachSinhVien.Count(x => x.Email.ToLower() == sinhVien.Email.ToLower()); var totalSoDienThoai = _context.DanhSachSinhVien.Count(x => x.SoDienThoai.ToLower() == sinhVien.SoDienThoai.ToLower()); IDictionary <string, string[]> Errors = new Dictionary <string, string[]>(); if (totalEmail >= 1 || totalSoDienThoai >= 1) { if (totalEmail >= 1) { Errors.Add("email", new string[] { "email is duplicated!" }); } if (totalSoDienThoai >= 1) { Errors.Add("soDienThoai", new string[] { "soDienThoai is duplicated!" }); } return(new ValidationResultDto { IsValid = false, Errors = Errors }); } else { return(new ValidationResultDto { IsValid = true }); } }
public async Task <IActionResult> Create(SinhVienForCreateDto sinhVien) { try { var validationResult = _repo.ValidateBeforeCreate(sinhVien); if (validationResult.IsValid) { var result = await _repo.Create(sinhVien); 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 } })); } }
public async Task <SinhVien> Create(SinhVienForCreateDto sinhVien) { var newSinhVien = new SinhVien { MaSinhVien = GenerateId(), HoVaTen = sinhVien.HoVaTen, MaLop = sinhVien.MaLop, GioiTinh = sinhVien.GioiTinh, NgaySinh = sinhVien.NgaySinh, Email = sinhVien.Email, QueQuan = sinhVien.QueQuan, DiaChi = sinhVien.DiaChi, SoDienThoai = sinhVien.SoDienThoai, ThoiGianTao = DateTime.Now, ThoiGianCapNhat = DateTime.Now, TrangThai = 1 }; await _context.DanhSachSinhVien.AddAsync(newSinhVien); await _context.SaveChangesAsync(); return(newSinhVien); }