Code First Table Migration - N for N using Fluent API

4

I have the following classes:

[Table("Area_Cursos_Turma")]
public class Turma
{
    public int TurmaID { get; set; }
    public virtual ICollection<Aluno> Alunos { get; set; }
}

[Table("Area_Cursos_Aluno")]
public class Aluno
{
    public int AlunoID { get; set; }
    public virtual ICollection<Turma> Turmas { get; set; }
}

Using Migration , it creates for me the table in the database: TurmaAluno , and would like it to create Area_Cursos_TurmaAluno .

I've tried the following:

modelBuilder.Entity<Aluno>()
    .HasMany(t=>t.Turmas)
    .WithMany(a => a.Alunos)
    .Map(m => m.MapLeftKey("Turma_TurmaID")
    .MapRightKey("Aluno_AlunoID")
    .ToTable("Area_Cursos_TurmaAluno"));

Apparently it worked. Is that right?

    
asked by anonymous 26.09.2014 / 14:06

1 answer

3

Yes it is. There is a slightly different alternative syntax:

modelBuilder.Entity<Aluno>()
    .HasMany(u => u.Turmas)
    .WithMany()
    .Map(m =>
    {
        m.MapLeftKey("Turma_TurmaID");
        m.MapRightKey("Aluno_AlunoID");
        m.ToTable("Area_Cursos_TurmaAluno");
    });

The problem is that this way you can not put extra properties in your associative table. In this case, you would have to model the associative table by putting the keys of the Student and Class entities in it, plus the extra columns.

    
26.09.2014 / 20:34