【问题标题】:Entity framework 5 foreign key mapping convention实体框架5外键映射约定
【发布时间】:2012-10-02 08:49:59
【问题描述】:

我有 2 个实体 Role 和 Permission 相应地具有一对多关联。

public class Role
{             
    public int Id { get; set; }

    public bool IsAdmin { get; set; }

    public virtual ICollection<Permission> Permissions { get; set; }
}

public class Permission
{
    public int Id { get; set; }

    public string Code { get; set; }

    public string GroupName { get; set; }

    public virtual Role Role { get; set; }    
}

并为它们创建了继承自EntityTypeConfiguration 类的映射类。

当我运行我的应用程序时,EF 为我创建了数据库,上面这些实体的外键是 Role_Id

我如何更改现有的或添加新的约定以摆脱外键中的下划线?

所以我想让 RoleId 作为我的实体的外键。

我不想使用数据注释属性,也不想向 Permission 类 (public int RoleId { get; set; }) 添加额外的属性,以便在这样的映射中使用它:
HasRequired(x =&gt; x.Role).WithMany(y =&gt; y.Permissions).HasForeignKey(o =&gt; o.RoleId);

谢谢,
阿列克谢

【问题讨论】:

    标签: code-first entity-framework-5


    【解决方案1】:

    实体框架目前不支持自定义全局约定,但您可以覆盖fluen API中的键名:

    modelBuilder.Entity<Permission>()
                .HasRequired(x => x.Role)
                .WithMany(y => y.Permissions)
                .Map(m => m.MapKey("RoleId"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多