First you should get rid of the RoleId
property in the User
model. Having that as a foreign key tells which single role a user has. Since a user can have many roles, the foreign key should not be in the user table but in the mapping table.
So what you have is a many-to-many relationship between users and roles, and Entity Framework
can create the needed mapping table automatically without you having to configure anything.
If you simply have a Roles
property in the User
entity and a Users
property in the Role
entity, EF will figure out that you want a many-to-many between those two, and create a table with the primary keys of both entities as a combined primary key, which will be used to map users to roles.
When loading a User
from the database you can then use the Roles
navigation property to figure out which roles the user has, and you can load a Role
to figure out which users are in that role.
The simplest way of making it work would be something like this:
public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
static Context()
{
Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
}
public Context()
: base("Server=localhost;Initial Catalog=Test;Integrated Security=True;")
{
}
}
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public List<Role> Roles { get; set; }
}
public class Role
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public List<User> Users { get; set; }
}
Running that code results in 3 tables like this: