Relationships with the Entity Framework?

0

Next, I'm modeling the domain class of a system and I'm having trouble understanding certain things of Entity Framework , so I hope you can help me by looking at what I'm following the idea of Code First :

In a relationship of N to M , doing so in the following way, will it automatically generate a new table or will I have to do this manually? If manually, how do I make this relationship?

public class Aluno {
   public int Id { get; set; }
   public virtual ICollection<Professor> Professores { get; set; }
}

public class Professor {
   public int Id { get; set; }
   public virtual ICollection<Aluno> Alunos { get; set; }
}
    
asked by anonymous 22.09.2017 / 19:47

1 answer

3

Using this tutorial as a reference , there can be two types of configuration.

Option 1 - Data Annotation

public class Aluno 
{
   public Aluno()
   {
      Professores = new HashSet<Professor>();
   }

   public int Id { get; set; }
   public virtual ICollection<Professor> Professores { get; set; }
}

public class Professor 
{    
   public Professor()
   {
      Alunos = new HashSet<Aluno>();
   }

   public int Id { get; set; }
   public virtual ICollection<Aluno> Alunos { get; set; }
}

In this case, that would be enough and relationships would be created correctly.

Option 2 - Fluent API

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<Aluno>()
                .HasMany<Professor>(s => s.Professores)
                .WithMany(c => c.Alunos)
                .Map(cs =>
                        {
                            cs.MapLeftKey("IdAluno");
                            cs.MapRightKey("IdProfessor");
                            cs.ToTable("AlunoProfessor"); // Nome da tabela
                        });
}
    
22.09.2017 / 19:57