Search code examples
c#entity-frameworkentity-framework-6many-to-many

How to rename an autogenerated n:m table in EF 6?


I set up a database using EF 6. I configured a many-to-many relationship successfully with the code seen below:

public class Software
{
    public string Id { get; set; }

    public string Version { get; set; }

    public string Name { get; set; }

    // Navigation property for machineSoftware
    public virtual ICollection<Machine> MachineSoftwares { get; set; }
}

public class Machine
{
    public int MachineId { get; set; }

    public string Model { get; set; }

    public string Customer { get; set; }

    public virtual ICollection<Software> MachineSoftwares { get; set; }
}

EF 6 created a third table MachineSoftwares automatically. So far so good.

Now I want to rename that table, but I don't have a corresponding class for that table that I could rename via migration. So how can I rename the table MachineSoftwares?


Solution

  • The name of the implicit many-to-many junction table (and the names of its columns) are configured through the Map Fluent API.

    But in order to get access to that API, you have to first map the relationship using a HasMany / WithMany pair:

    modelBuilder.Entity<Software>()
        .HasMany(e => e.MachineSoftwares)
        .WithMany(e => e.MachineSoftwares)
        .Map(config => config
            .ToTable("the_desired_table_name")
            //.MapLeftKey("SoftwareId") // in case you need different column names
            //.MapRightKey("MachineId")
        );