我需要在EF中模拟多对多的关系。 我经常遇到的答案要求两个实体互相引用。
这是我的情况。
我有一个Role实体,它可以有多个权限(“权限实体”。)Role将有一个名为权限的列表。另一方面,一个权限可以属于多个角色,但它没有role的引用属性。
我该如何建模呢?
另外,我可以使用Role级联新的权限吗?
I need to model a Many to many relation in EF. The answer I usually come across requires both entities to have each others reference.
Here is my case.
I have a Role entity, which can have multiple permissions("Permission entity). Role will have a list called permissions. On the other hand one permission can belong to multiple roles but it does not have a reference property for role.
How can I model it?
Also, can I cascade a new permission with Role?
最满意答案
使用Code-First,您可以使用此建模:
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; } }使用Fluent 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"); }); }Using Code-First you can go with this modeling:
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; } }Using Fluent Api you can map it like:
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"); }); }更多推荐
发布评论