2017-03-17 96 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"); 
         }); 

}