我得到了具有自定義MembershipProvider的MVC 3應用程序,因此它將新註冊的用戶存儲到我的數據庫中。 我對現有數據庫使用Code First方法(我爲此使用了實體框架電源工具)。有表用戶,角色和用戶角色。 在用戶表我: 用戶ID(PK) 用戶名密碼 電子郵件 ... 實體框架(代碼優先),多對多,用戶和角色
在表角色我 角色ID(PK) 名稱 說明
在表UsersRoles我 用戶ID(設爲複合PK) 角色ID(設爲複合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");
});
}
}
我在角色表中有預定義的角色,我不希望在新用戶註冊時修改它們(角色表只能由管理員修改),我希望將新用戶存儲在用戶表中,併爲其分配默認角色普通用戶(沒有特殊權限),因此它向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);
}
但我不知道如何使它添加一個新的記錄UsersRoles table..with用戶ID和角色ID(默認的,第一個角色ID = 1 - 普通用戶權限)。任何幫助將不勝感激。
如何不添加任何角色並假定沒有任何角色的用戶是普通用戶? – Oybek 2013-05-04 19:20:57