Insert combobox items using Entity Framework

Asked

Viewed 28 times

1

I have a Windowsforms application and I’m trying to insert items from a combobox and save to the database using Entity Framework Core. The biggest problem is that it inserts only one combobox item, even making a loop to go through the combobox information.

private void InserirDados()
        {
            ExemploDbContext context = new ExemploDbContext();
            Sala sala = new Sala();
            Aluno aluno = new Aluno();

            sala.NomeSala = textBox1.Text;

            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                sala.SalaAlunos = new List<SalaAluno>();
                sala.SalaAlunos.Add(new SalaAluno { AlunoId = Convert.ToInt32(listBox1.Items[i]) });
            }

            context.Add(sala);
            context.SaveChanges();
        }

Below the entities created

public class Sala
    {
        public int SalaId { get; set; }
        public string NomeSala { get; set; }

        public ICollection<SalaAluno> SalaAlunos { get; set; }
    }

public class Aluno
    {
        public int AlunoId { get; set; }
        public string NomeAluno { get; set; }

        public ICollection<SalaAluno> SalaAlunos { get; set; }
    }

public class SalaAluno
    {
        public int SalaAlunoId { get; set; }

        public int AlunoId { get; set; }
        public int SalaId { get; set; }
    }

1 answer

1


you are initiating the list with each loop iteration

    for (int i = 0; i < listBox1.Items.Count; i++)
    {
            sala.SalaAlunos = new List<SalaAluno>(); //<<<<<<<<<<<<<<<<<<<<<<<
            sala.SalaAlunos.Add(new SalaAluno { AlunoId = Convert.ToInt32(listBox1.Items[i]) });
    }

start the list before the for.

And you can also use async to not freeze the screen during the process, and use using for context to be dropped when no longer needed.

private async void InserirDados()
{
    using (ExemploDbContext context = new ExemploDbContext())
    {
        Sala sala = new Sala();
        sala.NomeSala = textBox1.Text;
        sala.SalaAlunos = new List<SalaAluno>();
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            sala.SalaAlunos.Add(new SalaAluno { AlunoId = Convert.ToInt32(listBox1.Items[i]) });
        }

        await context.AddAsync(sala);
        await context.SaveChangesAsync();
    }
}
  • 1

    I hadn’t noticed that detail, thank you very much!

Browser other questions tagged

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