Many to many relationships in EF5 Code First, how can I specify table name?

Conrad Clark picture Conrad Clark · Aug 2, 2012 · Viewed 9.3k times · Source

I'm quite new to EF, and I'm not really sure how to do this.

I have a many-to-many relationship, exactly like this:

enter image description here

When I try to add a resource (Recurso) to a profile (Perfil), I get the following error:

Invalid object name 'dbo.RecursoPerfils

Where the hell did RecursoPerfils come from?

How can I specify (preferably through attribute annotation) the table name for this relationship?

See the models below:

[Table("Perfil")]
public class Perfil
{
    public Perfil()
    {
        this.Usuarios = new List<Usuario>();
        this.Recursos = new List<Recurso>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int IdPerfil { get; set; }
    [Required]
    public string Descricao { get; set; }

    public virtual ICollection<Usuario> Usuarios { get; set; }
    public virtual ICollection<Recurso> Recursos { get; set; }
}

[Table("Recurso")]
public class Recurso
{
    public Recurso()
    {
        this.Perfis = new List<Perfil>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int IdRecurso { get; set; }
    [Required]       
    public string NomeRecurso { get; set; }
    [Required]
    public string Descricao { get; set; }
    public virtual ICollection<Perfil> Perfis { get; set; }
}

Answer

Eranga picture Eranga · Aug 2, 2012

You need to use Fluent API to configure the table name of the join table.

public class MyContext : DbContext
{
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Perfil>()
            .HasMany(p => p.Recursos)
            .WithMany(r => r.Perfis)
            .Map(mc =>
            {
                mc.MapLeftKey("IdPerfil");
                mc.MapRightKey("IdRecurso");
                mc.ToTable("PerfilRecurso");
            });
     }
}

You can go through this Fluent API relationship mapping tutorial for more info