Вопрос

I am experimenting with custom naming convenctions in EF 6. I have 2 tables and one junction table (WebUser, UserRequest, WebUserUserRequest).

I have written function that should be able to rename tables: from WebUser to web_user

private string GetTableName(Type type)
{
    var result = Regex.Replace(type.Name, ".[A-Z]", m => m.Value[0] + "_" + m.Value[1]);
    return result.ToLower();
}

It is applied this way:

        modelBuilder.Types()
            .Configure(c => c.ToTable(GetTableName(c.ClrType)));

The function is working fine on all tables except junction tables.

Source models:

WebUser, UserRequest

Resulting DB tables:

web_user, user_request, WebUserUserRequest (instead of web_user_user_request)

Is it possible to set junction naming convenction this way? Is there a way how to configure naming convection to process all the junction tables as described above (replace all uppercase and add "_")?

Это было полезно?

Решение

It is possible to add a convention this way that sets the associations with the Public Mapping API that was included in Entity Framework 6.1 To do that you have to implement the IStoreModelConvention interface in a similar way:

public class JunctionTableConvention : IStoreModelConvention<AssociationType>
{
    public void Apply(AssociationType item, DbModel model)
    {
        var associations = model.ConceptualToStoreMapping.AssociationSetMappings;

        foreach (var association in associations)
        {
            var associationSetEnds = association.AssociationSet.AssociationSetEnds;
            association.StoreEntitySet.Table = String.Format("{0}_{1}",
                GetTableName(associationSetEnds[0].EntitySet.ElementType),
                GetTableName(associationSetEnds[1].EntitySet.ElementType));
        }
    }

    private string GetTableName(EntityType type)
    {
        var result = Regex.Replace(type.Name, ".[A-Z]", m => m.Value[0] + "_" + m.Value[1]);
        return result.ToLower();
    }
}

And you have to include it in the OnModelCreating function of your DbContext implementation simply by adding it to the Conventions collection:

modelBuilder.Conventions.Add(new JunctionTableConvention());
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top