Code First Table Migration - N to N using Fluent API

Asked

Viewed 394 times

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 the Migration, he creates for me the table in the bank: TurmaAluno, and I would like him to create Area_Cursos_TurmaAluno.

I 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. That’s right?

1 answer

3


Yes. 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 have no way to put extra properties in your associative table. In this case, you would have to model the associative table by placing in it the keys of the Student and Class entities, plus the extra columns.

  • 1

    This is called Fluent API?

  • @Exact Diegozanardo. http://msdn.microsoft.com/en-us/data/jj591617.aspx

Browser other questions tagged

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