How to change the name of Many to Many (bridge) table generated by Entity Framework.

by Sachin Singh


Posted on Saturday, 13 February 2021

Tags: How to change the Name of Many to Many bridge table generated by Entity Framework

If an Entity A has a collection Navigation property of type Entity B and Entity B has a collection navigation property of Type Entity A, then Entity Framework generates a bridge or joining table, the name of the Joining table is the combination of singular Name of First Entity and Plural Name of second Entity.

Example: If there are two entity types ‘Customer’ and ‘Product’ then each customer can buy more than one product and a product can be bought by many different customers.


  public class Customer
   {
    public Customer() 
    {
        this.Product = new HashSet<Product>();
    }

    public int CustomerId { get; set; }
    [Required]
    public string CustomerName { get; set; }
    public virtual ICollection<Product> Products { get; set; }
  }
        
  public class Product
   {
    public Product ()
    {
        this.Customer = new HashSet<Customer>();
    }

    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
  }

EF API will create Customers, Products, and also the joining table CustomerProducts in the database for the above example. The CustomerProducts table will include the PK (Primary Key) of both tables - Customer_CustomerId & Product_ProductId.

Note: EF automatically creates a joining table with the name of both entities and the suffix 's', but Instead of CustomerOrders the joining table name should be Orders which will be more accurate, we can configure it using Fluent API, for this go to your DbContext class and override OnModelCreating() method as shown below.


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Customer>()
                          .HasMany<Product>(s => s.Product)
                          .WithMany(c => c.Customer)
                          .Map(cs =>
                          {
                             cs.MapLeftKey("CustomerId"); //key of 1st Entity
                            cs.MapRightKey("ProductId");// key of 2nd Entity
                            cs.ToTable("Order"); // Desired Name of Bridge table
                         });
              }