public async Task <ApplicationCondominium> CreateCondominiumAsync(ApplicationCondominium condominium) { try { var result = await _context.Condominium.AddAsync(condominium); if (result.State == EntityState.Added) { await _context.SaveChangesAsync(); } return(result.Entity); } catch (Exception ex) { throw; } }
public async Task <IActionResult> Add(AddCondominiumViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; int contPhone = 0; int contEmail = 0; model.Phones = model.Phones.Where(x => x != null && x.Phone != null).GroupBy(x => x.Phone).Select(y => y.First()).ToList(); model.Emails = model.Emails.Where(x => x != null && x.Email != null).GroupBy(x => x.Email).Select(y => y.First()).ToList(); Regex regexPhone = new Regex(@"^\([1-9]{2}\) (?:[2-8]|9[1-9])[0-9]{3}\-[0-9]{4}$"); Regex regexEmail = new Regex(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$"); foreach (var Phone in model.Phones.ToList().Select((value, index) => new { value, index })) { if (!regexPhone.IsMatch(Phone.value.Phone)) { model.Phones.RemoveAt(Phone.index - contPhone); contPhone++; } } foreach (var Email in model.Emails.ToList().Select((value, index) => new { value, index })) { if (!regexPhone.IsMatch(Email.value.Email)) { model.Emails.RemoveAt(Email.index - contEmail); contEmail++; } } if (ModelState.IsValid) { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Não é possível carregar o usuário com o ID '{_userManager.GetUserId(User)}'."); } var checkCNPJ = await _condominiumManager.CheckCNPJAsync(model.Cnpj); if (checkCNPJ == null) { var condominium = new ApplicationCondominium { CompanyName = model.CompanyName, FantasyName = model.FantasyName, Cnpj = model.Cnpj, ConstructionDate = model.ConstructionDate, CondominiumType = model.CondominiumType, Cep = model.Cep, Address = model.Address, City = model.City, District = model.District, Uf = model.Uf, Number = model.Number, Complement = model.Complement, Note = model.Note, User = user }; var verify = await _condominiumManager.CreateCondominiumAsync(condominium); if (verify != null) { foreach (var Phone in model.Phones) { var condominiumPhone = new ApplicationCondominiumPhone { Phone = Phone.Phone, Condominium = condominium }; await _condominiumManager.CreateCondominiumPhoneAsync(condominiumPhone); } foreach (var Email in model.Emails) { var condominiumEmail = new ApplicationCondominiumEmail { Email = Email.Email, Condominium = condominium }; await _condominiumManager.CreateCondominiumEmailAsync(condominiumEmail); } _toastNotification.AddSuccessToastMessage("Condomínio cadastrado com sucesso."); return(RedirectToAction("Index")); } } _toastNotification.AddErrorToastMessage("Já existe um condomínio cadastrado com esse CNPJ."); return(View(model)); } return(View(model)); }