Reputation: 947
I created:
It create me the 2 custom tables correctly. Now I want to create the table between Users and Roles with 2 columns: RoleId, UserId
I should I tweak my models to teach to EF to create this relationship table (UsersInRole)?
User model:
public class User
{
[Key]
public int UserId { get; set; }
[Required]
public Int32 CompanyId { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String Email { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLockedOut { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime LastLockoutDate { get; set; }
}
Role model:
public class Role
{
[Key]
public int RoleId { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
public ICollection<string> AssignedUsers { get; set; }
}
Upvotes: 0
Views: 2294
Reputation: 26727
public class Role
{
[Key]
public int RoleId { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
public ICollection<User> AssignedUsers { get; set; }
}
public class User
{
[Key]
public int UserId { get; set; }
[Required]
public Int32 CompanyId { get; set; }
[Required]
public String UserName { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String Email { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLockedOut { get; set; }
public DateTime CreateDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime LastPasswordChangedDate { get; set; }
public DateTime LastLockoutDate { get; set; }
public ICollection<Role> Roles{ get; set; }
}
Upvotes: 0
Reputation: 974
If you are using code-first EF, then all you should need to do is add a collection of the Users to the Role class and vice-versa. EF takes this two-way link as a signal to create a many-to-many relationship in the underlying data store. To summarize, your classes would be augmented something like this...
public class User
{
...
List<Role> Roles {get; set;}
}
public class Role
{
...
List<User> Users {get; set;}
}
Upvotes: 1