使用VS2013创建MVC4项目后,自动生成的代码中默认使用WebSecurity模型创建用户管理,生成以下数据库:
用户信息只有ID和UserName,角色信息也只有两个基础字段。通常情况下这样的数据表不能满足我们的需求,因此对其进行扩展。
首先定义自己的用户信息、角色信息结构。
1 [Table("UserProfile")]
2 public class UserProfile
3 {
4 [Key]
5 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
6 [Column(Order = 0)]
7 public int UserId { get; set; }
8
9 [Column(Order = 1)]
10 [Required]
11 public string UserName { get; set; }
12
13 [Column(Order = 2)]
14 public string UserCode { get; set; }
15
16 [Column(Order = 3)]
17 public int Status { get; set; }
18
19 [Column(Order = 4)]
20 public string Email { get; set; }
21
22 [Column(Order = 5)]
23 public int? Gender { get; set; }
24
25 [Column(Order = 6)]
26 public int? CreatorId { get; set; }
27
28 public virtual ICollection<Role> Roles { get; set; }
29 }
30
31 /// <summary>
32 /// 角色信息为树状结构
33 /// </summary>
34 [Table("webpages_Roles")]
35 public class Role
36 {
37 [Key]
38 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
39 [Column(Order = 0)]
40 public int RoleId { get; set; }
41
42 [Column(Order = 1)]
43 public int? ParentId { get; set; } //父级角色ID
44
45 [Required]
46 [Column(Order = 2)]
47 public string RoleName { get; set; }
48
49 [Column(Order = 3)]
50 public int TreeLevel { get; set; }
51
52 [Column(Order = 4)]
53 public string TreePath { get; set; }
54
55 [Column(Order = 5)]
56 public int Status { get; set; }
57
58 [Column(Order = 6)]
59 public string Description { get; set; }
60
61 [ForeignKey("ParentId")]
62 public virtual Role Parent { get; set; }
63
64 [InverseProperty("Parent")]
65 public virtual ICollection<Role> Children { get; set; }
66
67 public virtual ICollection<UserProfile> Users { get; set; }
68 }
创建数据库上下文类型UsersContext:
1 public class UsersContext: DbContext, IDisposable
2 {
3 #region 数据表映射实例
4 public DbSet<UserProfile> UserProfiles { get; set; }
5
6 public DbSet<Role> Roles { get; set; }
7 #endregion
8
9 #region 构造
10 public UsersContext() : base("DefaultConnection") { }
11
12 public UsersContext(string connectionString) : base(connectionString) { }
13 #endregion
14
15 #region 事件
16 protected override void OnModelCreating(DbModelBuilder modelBuilder)
17 {
18 //配置用户角色关系表
19 modelBuilder.Entity<Role>().HasMany(p => p.Users).WithMany(p => p.Roles).Map(m => { m.ToTable("webpages_UsersInRoles"); m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); });
20 base.OnModelCreating(modelBuilder);
21 }
22 #endregion
23
24 #region 析构
25 public event EventHandler Disposed;
26
27 public bool IsDisposed { get; private set; }
28
29 public new void Dispose()
30 {
31 Dispose(true);
32 }
33
34 protected new void Dispose(bool disposing)
35 {
36 lock (this)
37 {
38 if (disposing && !IsDisposed)
39 {
40 base.Dispose();
41 var evt = Disposed;
42 if (evt != null) evt(this, EventArgs.Empty);
43 Disposed = null;
44 IsDisposed = true;
45 GC.SuppressFinalize(this);
46 }
47 }
48 }
49 #endregion
50 }
修改站点项目Filters目录下的InitializeSimpleMembershipAttribute.cs文件中的构造器。
1 private class SimpleMembershipInitializer
2 {
3 public SimpleMembershipInitializer()
4 {
5 Database.SetInitializer<Framework.DomainModels.UsersContext>(null); //这里使用我们刚刚定义的数据库上下文
6
7 try
8 {
9 using (var context = new Framework.DomainModels.UsersContext()) //这里使用我们刚刚定义的数据库上下文
10 {
11 if (!context.Database.Exists())
12 {
13 // Create the SimpleMembership database without Entity Framework migration schema
14 ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
15 }
16 }
17
18 WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
19 }
20 catch (Exception ex)
21 {
22 throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
23 }
24 }
25 }
删除原有数据库,重新运行项目,点击注册按钮,这时生成新的数据库。
在提交注册用户之前,让我们再做一些修改。找到AccountController下的Register方法(Post类型),对其进行以下修改:
1 [HttpPost]
2 [AllowAnonymous]
3 [ValidateAntiForgeryToken]
4 public ActionResult Register(RegisterModel model)
5 {
6 if (ModelState.IsValid)
7 {
8 // Attempt to register the user
9 try
10 {
11 WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Status = 1 /* 在UserProfile表中,该字段为必填。如还有其它必填字段,只需在此添加即可 */ });
12 WebSecurity.Login(model.UserName, model.Password);
13 return RedirectToAction("Index", "Home");
14 }
15 catch (MembershipCreateUserException e)
16 {
17 ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
18 }
19 }
20
21 // If we got this far, something failed, redisplay form
22 return View(model);
23 }
运行项目,注册用户:
OK,我们的用户信息及角色信息扩展成功!
.NET MVC4 实训记录之二(扩展WebSecurity模型下的UserProfile表),布布扣,bubuko.com
.NET MVC4 实训记录之二(扩展WebSecurity模型下的UserProfile表)
原文:http://www.cnblogs.com/libra1006/p/3896096.html