0

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?

Jajan
  • 887
  • 3
  • 15
  • 28
  • How are you creating your model? Code-first, model-first...? – vesan Mar 17 '17 at 03:27
  • I am using Code First.. – Jajan Mar 17 '17 at 03:28
  • I'm not sure if it's possible to do without having the "Roles" property on your permissions class. You can always add the property and simply not use it. Check out this tutorial: http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx – vesan Mar 17 '17 at 03:32
  • Otherwise you would probably have to create the linking table ("RolePermissions" or something like that) manually similar to this: http://stackoverflow.com/questions/7050404/create-code-first-many-to-many-with-additional-fields-in-association-table – vesan Mar 17 '17 at 03:32
  • Yeah I saw that link..Thanks..I was just wondering if there was a way without using two way references... – Jajan Mar 17 '17 at 04:29

1 Answers1

1

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");
                        });

}
Masoud Andalibi
  • 3,168
  • 5
  • 18
  • 44