Phone Array Update in Database

0

I'm trying to update information in my database where I have 1:N between Clientes and Telefones , but I'm not able to perform such an update because sometimes it will be necessary to remove a phone that is in the database , sometimes add a new phone and keep those that are already inserted, and sometimes will need to perform the two operations together, could you help me?

My Controller:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(EditClientViewModel model)
    {
        if (ModelState.IsValid)
        {
            var client = await _clientManager.GetClientIdAsync(model.Id);

            if (client == null)
            {
                throw new ApplicationException($"Não é possível carregar o cliente com o ID '{client.Id}'.");
            }

            client.Nome = model.Name;
            client.RazaoSocial = model.CompanyName;
            client.NomeFantasia = model.FantasyName;
            client.Cpfj = model.Cpfj;
            client.CEP = model.CEP;
            client.UF = model.UF;
            client.Bairro = model.Neighborhood;
            client.Cidade = model.City;
            client.Endereco = model.Address;
            client.Numero = model.Number;
            client.Complemento = model.Complement;
            client.DataNascimento = model.BirthDate;
            client.TipoPessoa = model.TypePerson;

            var result = await _clientManager.UpdateClientAsync(client);

            foreach (var ClientTelephone in client.ClientesTelefone)
            {
                foreach (var NewClientTelephone in model.Telephone)
                {
                    if(ClientTelephone.ToString() != NewClientTelephone && NewClientTelephone != null)
                    {
                        var clientTelephone = new ApplicationClientTelephone
                        {
                            Telefone = NewClientTelephone,
                            Cliente = client
                        };

                        await _clientManager.UpdateClientTelephoneAsync(clientTelephone);
                    }
                }
            }

            TempData["MensagemSucesso"] = "Cliente alterado com sucesso";

            return RedirectToAction("Index");
        }

        return View(model);
    }
    
asked by anonymous 26.09.2018 / 20:08

0 answers