2017-03-17 95 views
0

我需要建模EF中的多对多关系。我通常遇到的答案要求两个实体互相参照。实体框架中的多对多

这是我的情况。

我有一个角色实体,它可以拥有多个权限(“权限实体)。角色将有一个名为权限的列表。另一方面,一个权限可以属于多个角色,但它没有角色的引用属性。

我如何可以模拟它

而且,我可以用级联角色的新权限

+0

你如何创建模型?代码优先,模型优先...? – vesan

+0

我正在使用Code First .. – Jajan

+0

我不确定是否可以在您的权限类中没有“角色”属性。你可以随时添加该属性,而不是使用它。看看这个教程:http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx – vesan

回答

1

使用代码首先,你可以用这个模型去:??

public class Role 
{ 
    public Role() 
    { 
     this.Premission = new HashSet<Premission>(); 
    } 

    public int RoleId { get; set; } 
    public string RoleName { get; set; } 

    public virtual ICollection<Premission> Premissions { get; set; } 
} 

public class Premission 
{ 
    public Premission() 
    { 
     this.Role = new HashSet<Role>(); 
    } 

    public int PremissionId { get; set; } 
    public string PremissionName { get; set; } 

    public virtual ICollection<Role> Roles{ get; set; } 
} 

使用流利的API,您可以映射它想:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 

    modelBuilder.Entity<Role>() 
       .HasMany<Premission>(s => s.Premissions) 
       .WithMany(c => c.Roles) 
       .Map(cs => 
         { 
          cs.MapLeftKey("RoleRefId"); 
          cs.MapRightKey("PremissionRefId"); 
          cs.ToTable("Role_Premission"); 
         }); 

}