【问题标题】:EF 6, code first junction table nameEF 6,代码第一个联结表名
【发布时间】:2017-07-20 17:49:16
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    可以通过这种方式添加一个约定,以设置与 Entity Framework 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());
    

    【讨论】:

    • 有一个当之无愧的上船朋友!
    • 谢谢老兄,感激不尽!
    • 终于让我在 Oracle 中使用 EF 制作不带引号的表格以及 stackoverflow.com/a/35457202/631527
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2013-12-26
    相关资源
    最近更新 更多