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; }
}
I hadn’t noticed that detail, thank you very much!
– Igor Campina