Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
}
like image 328
Conrad Clark Avatar asked Aug 02 '12 01:08

Conrad Clark


People also ask

How do I map a one-to-many relationship in Entity Framework?

“HasMany” and “WithMany” method is used to define one-to-many or many-to-many relation in entity framework. We can configure one-to-many relationships between People and PeopleAddress using Fluent API by the following code in the model class: protected override void OnModelCreating(DbModelBuildermodelBuilder) {

How will you create relationship between tables in Entity Framework?

You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.


1 Answers

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

like image 174
Eranga Avatar answered Oct 12 '22 02:10

Eranga