I’m quite new to using the entity framework and I’m having trouble getting my head around how to write a query that uses a many to many relationship. I have 3 entities. Role, User and Securable. A Role can have multiple Securables, and a Securable can be assigned to many Roles. A Role can have multiple Users, and a User can have multiple Roles.
My Question is: How would I go about writing a query that gave me a distinct list of Securables for a given user ID?
Here is my model, where EF automatically creates the link tables for me.
public class SecurityContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Securable> Securables { get; set; }
}
public class User
{
public Guid UserId { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class Securable
{
public Guid SecurableId { get; set; }
public string Name { get; set; }
public virtual ICollection<Role> Roles { get;set;}
}
public class Role
{
public Guid RoleId { get; set; }
public string Name { get; set; }
public virtual ICollection<Securable> Securables { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Untested, but off the top of my head it would be something like this: