2

我正在 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)));

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

源模型:

网络用户、用户请求

生成的数据库表:

web_user、user_request、WebUserUserRequest(而不是 web_user_user_request)

是否可以通过这种方式设置连接命名约定?有没有办法配置命名对流来处理如上所述的所有联结表(替换所有大写并添加“_”)?

4

1 回答 1

3

可以通过这种方式添加一个约定,以设置与实体框架 6.1 中包含的公共映射 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();
    }
}

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

modelBuilder.Conventions.Add(new JunctionTableConvention());
于 2014-05-19T19:00:58.920 回答