Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.2 Code First. How to name a many-to-many table?

Is it possible to specify the table name in a many-to-many relationship?

Example:

class A
{
    public int Id { get; set; }
    // .....

    public virtual ICollection<B> BCollection { get; set; }
}

class B
{
    public int Id { get; set; }
    // .....

    public virtual ICollection<A> ACollection { get; set; }
}

I thought that this could maybe work but apparently it doesn't.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<A>().HasMany(x => x.BCollection).WithMany(y => y.ACollection).Map(m => m.ToTable("My_Custom_Name"));
}
like image 513
Patrick Avatar asked Dec 17 '22 05:12

Patrick


1 Answers

Try maapping the column names also.

        modelBuilder.Entity<A>()
        .HasMany(x => x.BCollection).WithMany(y => y.ACollection)
            .Map(m =>
            {
                m.ToTable("My_Custom_Name");
                m.MapLeftKey("AId");
                m.MapRightKey("BId");
            });
like image 161
Eranga Avatar answered Jan 05 '23 15:01

Eranga