EF 6,代码第一个联结表名称

时间:2014-05-15 12:24:20

标签: entity-framework ef-code-first naming-conventions junction

我正在尝试使用EF 6中的自定义命名约定。我有2个表和一个联结表(WebUser,UserRequest,WebUserUserRequest)。

我编写了应该能够重命名表的函数:从WebUser到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();
}

以这种方式应用:

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

该功能在除联结表之外的所有表上都能正常工作。

来源型号:

WebUser,UserRequest

生成的数据库表:

web_user,user_request,WebUserUserRequest(而不是web_user_user_request)

是否可以通过这种方式设置联结命名协议?有没有办法如何配置命名对流来处理所有联结表,如上所述(替换所有大写并添加" _")?

1 个答案:

答案 0 :(得分:3)

可以通过这种方式添加约定,以设置与Entity Framework 6.1中包含的Public Mapping API的关联。为此,您必须以类似的方式实现IStoreModelConvention接口:

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

只需将其添加到Conventions集合中,您就必须将它包含在DbContext实现的OnModelCreating函数中:

modelBuilder.Conventions.Add(new JunctionTableConvention());
相关问题