【问题标题】:Change EF6 key FK convention更改 EF6 密钥 FK 约定
【发布时间】:2015-08-19 20:14:36
【问题描述】:

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

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

【问题讨论】:

  • MSDN 在这里有一个创建自定义 ForeignKeyNamingConvention 的示例:msdn.microsoft.com/en-us/data/dn469439.aspx#example2 ...我还没有尝试过,但它可能是你可以构建的东西。
  • @Peter 谢谢!工作完美!您介意张贴作为答案,以便我接受吗?
  • 太棒了!随时使用适合您的代码更新我的答案(或发布并接受您自己的答案)。我相信它会对其他用户有用。

标签: c# entity-framework entity-framework-6 naming-conventions


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-22
        • 2019-10-21
        • 2015-04-05
        • 2014-12-28
        • 2013-05-29
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多