Relationships with the Entity Framework?

Asked

Viewed 64 times

0

Next, I’m modeling the domain class of a system and I’m having a hard time understanding certain things from Entity Framework, so I hope you can help me, aiming that I’m following the idea of Code First:

In a relationship of N for M, Doing this, will it generate a new table automatically or will I have to do it 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; }
}

1 answer

3

Using this tutorial as a reference, there may 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 the 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
                        });
}

Browser other questions tagged

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