简体   繁体   English

实体框架(代码优先),多对多,用户和角色

[英]Entity framework (code first), many to many, users and roles

I got MVC 3 application with custom MembershipProvider, so it stores newly registered users to my database. 我使用自定义MembershipProvider获得了MVC 3应用程序,因此它将新注册的用户存储到我的数据库中。 I'm using Code First approach with existing database (I've used entity framework power tools for this). 我在现有数据库中使用了代码优先方法(为此,我使用了实体框架强大的工具)。 Got tables Users, Roles and UsersRoles. 得到了表Users,Roles和UsersRoles。 In table Users I got: UserID (PK) Username Password Email ... 在我获得的表Users中:UserID(PK)用户名密码电子邮件...

In table Roles I got RoleID (PK) Name Description 在“角色”表中,我获得了RoleID(PK)名称描述

In table UsersRoles I got UserID (set as composite PK) RoleID (set as composite PK) 在表UsersRoles中,我获得了UserID(设置为复合PK)RoleID(设置为复合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. 我在“角色”表中具有预定义的角色,并且我不希望在新用户注册时修改它们(角色表应仅由管理员修改),我希望将新用户存储在“用户”表中并为其分配常规角色的默认角色用户(没有特殊特权),因此它将一条记录添加到Users表+ UsersRoles表中的一条记录。

   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). 但是我不知道如何使它添加到具有UserID和RoleID(默认值,第一个RoleID = 1-普通用户权限)的UsersRoles表中的新记录。 Any help will be appreciated. 任何帮助将不胜感激。

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. EF将在联结表中创建一个新记录。 Note that the Users collection must be loaded at this point. 请注意,此时必须加载Users集合。

Doing so, you don't even need the statement Users.Add(user); 这样做,您甚至不需要语句Users.Add(user); to save the user. 保存用户。

Likewise you can add a role object to user.Roles . 同样,您可以向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 . 当您要删除联结表中的记录时,请从已加载的 user.Roles集合中删除一个角色,或者从role.Users删除一个用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM