0

I created:

  • custom custom membership provider
  • custom role provider
  • an user model
  • an role model

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

}

2 Answers 2

1

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;}
}
Sign up to request clarification or add additional context in comments.

Comments

0
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; }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.