0
votes

I got MVC 3 application with custom MembershipProvider, so it stores newly registered users to my database. I'm using Code First approach with existing database (I've used entity framework power tools for this). Got tables Users, Roles and UsersRoles. In table Users I got: UserID (PK) Username Password Email ...

In table Roles I got RoleID (PK) Name Description

In table UsersRoles I got UserID (set as composite PK) RoleID (set as composite PK)

 public partial class User
 {
    public User()
    {
        this.Roles = new List<Role>();
    }

    public int UserID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
}

public partial class Role
{
    public Role()
    {
        this.Users = new List<User>();
    }
    public int RoleID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<User> Users { get; set; }
}


public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        // Primary Key
        this.HasKey(t => t.UserID);

        // Properties
        this.Property(t => t.Username)
            .IsRequired()
            .HasMaxLength(20);

        this.Property(t => t.Password)
            .IsRequired()
            .HasMaxLength(50);

        this.Property(t => t.Email)
            .IsRequired()
            .HasMaxLength(100);



        // Table & Column Mappings
        this.ToTable("Users");
        this.Property(t => t.UserID).HasColumnName("UserID");
        this.Property(t => t.Username).HasColumnName("Username");
        this.Property(t => t.Password).HasColumnName("Password");
        this.Property(t => t.Email).HasColumnName("Email");

    }
}

public class RoleMap : EntityTypeConfiguration<Role>
{
    public RoleMap()
    {
        // Primary Key
        this.HasKey(t => t.RoleID);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(20);

        this.Property(t => t.Description)
            .HasMaxLength(50);

        // Table & Column Mappings
        this.ToTable("Roles");
        this.Property(t => t.RoleID).HasColumnName("RoleID");
        this.Property(t => t.Name).HasColumnName("Name");
        this.Property(t => t.Description).HasColumnName("Description");

        // Relationships
        this.HasMany(t => t.Users)
            .WithMany(t => t.Roles)
            .Map(m =>
                {
                    m.ToTable("UsersRoles");
                    m.MapLeftKey("RoleID");
                    m.MapRightKey("UserID");
                });


    }
}

I have predefined roles in Roles table and I don't want them to be modified when new users registers (Roles table should be only modified by administrator), I want new user to be stored in Users table and assign him default role of a regular user (with no special privileges), so it adds a record to Users table + a record in UsersRoles table.

   public void AddUser(User user)
    {   
        Users.Add(user);
        SaveChanges();
   }

 var tmp = new User { Username = username, Password = GetMd5Hash(password), Email = email };


            using (var db = new mycontext())
            {
                mycontext.AddUser(userObj);
            }

But I have no idea how to make it add a new record to UsersRoles table..with UserID and RoleID (default one, the first one RoleID=1 - normal user privileges). Any help will be appreciated.

1
How about not adding any role and assuming that the user without any role is a regular user?Oybek

1 Answers

0
votes

You just fetch the required role from the database and the you do

role.Users.Add(user);
SaveChanges();

EF will create a new record in the junction table. Note that the Users collection must be loaded at this point.

Doing so, you don't even need the statement Users.Add(user); to save the user.

Likewise you can add a role object to user.Roles.

When you want to remove a record in the junction table you remove a role from the loaded user.Roles collection or a user from role.Users.