[英]Change EF6 key FK convention
EF默认将我的FK命名为EntityName_id
,我希望将其命名为id_EntityName
。 我怎样才能做到这一点?
编辑1:
这里有700多个FK ...自动化这将使我相信快得多...也打算使用相同的答案来标准化复合PK ...
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.