Reputation: 926
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?
Upvotes: 0
Views: 69
Reputation: 3228
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");
});
}
Upvotes: 1