更改EF6键FK约定

本文关键字:约定 FK EF6 更改 | 更新日期: 2023-09-27 18:08:43

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

Edit1:
这里有超过700名fk…我相信自动化会快得多……还打算使用相同的答案来规范化组合PKs…

更改EF6键FK约定

MSDN有一个创建自定义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>();  
} 

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

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