EF默认将我的FK命名为EntityName_id
,我希望将其命名为id_EntityName
。我怎么能这样做?
EDIT1:
这里有超过700个FK ...自动化这个我会相信更快...还打算使用相同的答案来规范化复合PK ...
答案 0 :(得分:2)
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>();
}
答案 1 :(得分:1)
我认为最好的方法是使用流畅的映射,例如
.Map(m => m.MapKey("id_EntityName")
答案 2 :(得分:0)
您可以通过为实体设置映射来完成此操作。
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());
}