EF 6, code first junction table name

霸气de小男生 提交于 2021-02-10 10:52:07

问题


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 "_")?


回答1:


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());


来源:https://stackoverflow.com/questions/23678155/ef-6-code-first-junction-table-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!