0
I’m trying to update information in my database where I have 1:N
amid Clientes
and Telefones
, but I am not able to perform such update, because sometimes it will be necessary to remove a phone that is in the bank, sometimes add a new phone and keep those that are already inserted, and sometimes it will be necessary to perform the two joint operations, could 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);
}
One way out is to remove all phones and insert the ones in the list. But if you want to have control of when a number has been changed, you will have to store the
id
of every phone, then you do the treatment, if there isid
agoupdate
, otherwise, doesinsert
. It seemed?– Roberto de Campos
I thought about this way of removing everything and adding everything again, but I couldn’t do the
Remove()
, tried as hard asRemove
how muchRemoveRange
, but I don’t think I’ve developed such a function properly– Matheus
Make a query, remove Ids that no longer exist and update the rest
– Leandro Angelo