How to change the naming convention of Many-to-Many table relationships?

ef-code-first entity-framework entity-framework-6


How can I go about changing the naming convention of the auto-generated many-to-many table?

Assume I have two classes:

public class User
    public int UserId { get; set; }
    public virtual List<Role> Roles { get; set; }

public class Role
    public int RoleId { get; set; }
    public virtual List<User> Users { get; set; }

By Default, this will create a table called UserRoles.

I can change the name of that one table to UsersInRoles, for example, by using the following in the OnModelCreating override of my DbContext:

    .HasMany(p => p.Roles)
    .WithMany(p => p.Users)
    .Map(mc =>

However, what I really want to do is change the naming convention so that by default, all auto-generated many-to-many tables use this new convention. I cannot figure out how to do that, or if it's even possible. I do not like having to specify 9 lines of extra code every time I specify one of these relationships.

I am currently using EF version 6.0.0-rc1.

7/21/2015 6:27:24 AM

Accepted Answer

The ability to control relationships was removed from the basic conventions API before release because it wasn't in a usable state. You can access all of the properties and tables in the model through model based conventions. An overview of model based conventions is available here:

This solution involves a little more digging around in the metadata API, EntitySet is the correct type for this scenario

This convention should rename the generated relation table:

public class MyConvention : IStoreModelConvention<EntitySet>
    public void Apply(EntitySet set, DbModel model)
        var properties = set.ElementType.Properties;
        if (properties.Count == 2)
            var relationEnds = new List<string>();
            int i = 0;
            foreach (var metadataProperty in properties)
                if (metadataProperty.Name.EndsWith("_ID"))
                    var name = metadataProperty.Name;
                    relationEnds.Add(name.Substring(0, name.Length - 3));
            if (relationEnds.Count == 2)
                set.Table = relationEnds.ElementAt(0) + "_" + relationEnds.ElementAt(1) + "_RelationTable";
10/17/2013 5:01:56 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow