Save Phone Array to Database

Asked

Viewed 116 times

2

I created a table of Clientes and two from customers who are ClientesTelefone and ClientesEmail in my form I am generating email fields and phone dynamically, so I would like to know how I can receive and record these values in the tables, could help me please ??

ApplicationClient: here create the customer.

public async Task<ApplicationClient> CreateClientAsync(ApplicationClient client)
    {
        try
        {
            var result = await _context.Clientes.AddAsync(client);

            if (result.State == EntityState.Added)
            {
                _context.SaveChanges();
            }

            return result.Entity;

        }
        catch (Exception)
        {

            throw;
        }
    }

Clientcontroller:

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 client = new ApplicationClient {
                TipoPessoa = model.TypePerson,Nome = model.Name,
                RazaoSocial = model.CompanyName, NomeFantasia = model.FantasyName,
                Cpfj = model.Cpfj, CEP = model.CEP, UF = model.UF,
                Bairro = model.Neighborhood, Cidade = model.City,
                Endereco = model.Address, Numero = model.Number,
                Complemento = model.Complement, InfoAdicionais = model.AddInformation,
                DataNascimento = model.BirthDate, UsuarioId = user.Id
            };

            var result = await _clientManager.CreateClientAsync(client);

            var clientTelephone = new ApplicationClientTelephone
            {
                Telefone = model.Telephone

            };

            var clientEmail = new ApplicationClientEmail
            {
                Email = model.Email
            };

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

            return View("Index");
        }

Applicationclient:

public class ApplicationClient
{
    [Key]
    public Guid Id { get; set; }

    public String Nome { get; set; }

    public Guid UsuarioId { get; set; }

    public virtual ICollection<ApplicationClientTelephone> ClientesTelefone { get; set; }

    public virtual ICollection<ApplicationClientEmail> ClientesEmail { get; set; }

    [ForeignKey("UsuarioId")]
    public virtual ApplicationUser Usuario { get; set; }

}

I own ApplicationClientTelephone And ApplicationClientEmail.

I would like after the customer was added, to start generating a chain reaction that would add the customer’s phone and emails.

If you can help me I really appreciate.

  • How is the mapping of their entities? If possible edit the question and put them to check, usually the mapping is correct and already contain in the customer the email list and phone will already in chain add in the database.

  • Reply Edited friend.

  • It is that in the case, the user can add only n phones, that way I would have to have a loop adding the phones I don’t know if you understood me

  • I answered the question and added two ways to insert phone and email, one with loop and one with only 1 item in each list

1 answer

0

Before this Call add your phones and emails to the list

var result = await _clientManager.CreateClientAsync(client);

The code should be next to that

clientTelephone.ClientesTelefone = new List<ApplicationClientTelephone>(){
   new ApplicationClientTelephone
   {
      Telefone = model.Telephone
   }
};

clientTelephone.ClientesEmail = new List<ApplicationClientEmail>(){
   new ApplicationClientEmail
   {
      Email = model.Email
   }
};

var result = await _clientManager.CreateClientAsync(client);

If you want to add more than one email or phone you should do a for and call the Add() method of the lists to add the items, assuming which model. Email and model.Phone be lists.

clientTelephone.ClientesTelefone = new List<ApplicationClientTelephone>();
clientTelephone.ClientesEmail = new List<ApplicationClientEmail>();

foreach(var telefone in model.Telefone)
{
    clientTelephone.ClientesTelefone.Add(new ApplicationClientTelephone() { Telefone = telefone });
}

foreach(var email in model.Email)
{
    clientTelephone.ClientesEmail.Add(new ApplicationClientEmail() { Email = email });
}

var result = await _clientManager.CreateClientAsync(client);
  • new <ApplicationClientEmail>{} ?

  • @Leandroangelo corrected, as I’m typing outside the visual studio I ended up forgetting the List<>

  • I have not created the data as list yet, I just tried to receive the html form, searching the internet I found some examples using string[] values = Request.Form.GetValues("textBoxes"); I’m trying to adapt your solution to my problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.