首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改EF6密钥FK约定

更改EF6密钥FK约定
EN

Stack Overflow用户
提问于 2015-08-19 20:14:36
回答 3查看 74关注 0票数 0

默认情况下,EF将我的FKs命名为EntityName_id,我希望它被命名为id_EntityName。我怎么能这么做?

Edit1:

这里有700多个FKs ..。自动化这会更快我相信..。还打算用同样的答案来规范复合PKs.

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-08-20 15:41:02

MSDN有一个创建自定义ForeignKeyNamingConvention的示例。。您可以根据约定修改此示例以命名Foreign。

我还没有测试过这一点,但是这里有一些您可能可以构建的粗略代码:

代码语言:javascript
复制
public class ForeignKeyNamingConvention : IStoreModelConvention<AssociationType>
{
    public void Apply(AssociationType association, DbModel model)
    {
        if (association.IsForeignKey)
        {
            var constraint = association.Constraint;

            for (int i = 0; i < constraint.ToProperties.Count; ++i)
            {
                int underscoreIndex = constraint.ToProperties[i].Name.IndexOf('_');
                if (underscoreIndex > 0)
                {
                    // change from EntityName_Id to id_EntityName
                    constraint.ToProperties[i].Name = "id_" + constraint.ToProperties[i].Name.Remove(underscoreIndex);
                } 
            }
        }
    }
}

然后,您可以在DbContext's OnModelCreating()方法中注册您的自定义约定,如下所示:

代码语言:javascript
复制
protected override void OnModelCreating(DbModelBuilder modelBuilder)  
{  
    modelBuilder.Conventions.Add<ForeignKeyNamingConvention>();  
} 
票数 2
EN

Stack Overflow用户

发布于 2015-08-19 20:29:59

我认为最好的方法是使用fluent映射,例如

代码语言:javascript
复制
.Map(m => m.MapKey("id_EntityName")
票数 1
EN

Stack Overflow用户

发布于 2015-08-19 20:32:52

您可以通过为实体设置映射来做到这一点。

代码语言:javascript
复制
public class User
{
     public int Id {get;set;}
     public virtual Address Address {get;set;}


}

public class Address
{
     public int Id {get;set;}
     //Some other properties
}




public class UserMapping: EntityTypeConfiguration<User>
{
    public UserMapping()
    {
         HasOptional(u => u.Address).WithMany()
                                   .Map(m => m.MapKey("Id_Address"));

    }
}

//Override the OnModelCreating method in the DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
      modelBuild.Configurations.Add(new UserMapping());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32104831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档