Code First Table Migration – N for N using Fluent API

Posted on

Question :

I have the following classes:

public class Turma
    public int TurmaID { get; set; }
    public virtual ICollection<Aluno> Alunos { get; set; }

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:

    .WithMany(a => a.Alunos)
    .Map(m => m.MapLeftKey("Turma_TurmaID")

Apparently it worked. Is that right?


Answer :

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

    .HasMany(u => u.Turmas)
    .Map(m =>

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.


Leave a Reply

Your email address will not be published. Required fields are marked *