更改 EF6 键 FK 约定

Change EF6 key FK convention

EF 默认将我的 FK 命名为 EntityName_id,我希望将其命名为 id_EntityName。我该怎么做?

编辑1:
这里有 700 多个 FK...自动化这会快很多我相信...还打算使用相同的答案来标准化复合 PK...

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

.Map(m => m.MapKey("id_EntityName")

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

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

MSDN has an example of creating a custom ForeignKeyNamingConvention。您可以修改此示例以根据您的约定命名外键。

我还没有对此进行测试,但这里有一些您可以构建的粗略代码:

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() 方法中注册您的自定义约定,如下所示:

protected override void OnModelCreating(DbModelBuilder modelBuilder)  
{  
    modelBuilder.Conventions.Add<ForeignKeyNamingConvention>();  
}