ASP.NET Identity “角色-权限”管理 4
1.1. User-Role分析
想必大家已经注意到了Microsoft.AspNet.Identity.EntityFramework是对Microsoft.AspNet.Identity.Core的EF实现,微软是如何处理IdentityUser与IdentityRole的关系?因两者为多对多关系,会在关系型数据库增加一张关联表,故增加IdentityUserRole,并在IdentityUser与IdentityRole中添加IdentityUserRole列表,代码如下所示。
public class IdentityUserRole<TKey> { public virtual TKey RoleId { get; set; }
public virtual TKey UserId { get; set; } } |
IdentityUser
public class IdentityUser<TKey, TLogin, TRole, TClaim> : IUser<TKey> where TLogin: IdentityUserLogin<TKey> where TRole: IdentityUserRole<TKey> where TClaim: IdentityUserClaim<TKey> { public IdentityUser() { this.Roles = new List<TRole>(); } public ICollection<TRole> Roles { virtual get; private set; } 其它代码省略…. } |
IdentityRole
public class IdentityRole<TKey, TUserRole> : IRole<TKey> where TUserRole: IdentityUserRole<TKey> { public IdentityRole() { this.Users = new List<TUserRole>(); }
public TKey Id { get; set; }
public string Name { get; set; }
public ICollection<TUserRole> Users { virtual get; private set; } } |
EF分别配置IdentityUser、IdentityRole与IdentityUserRole的1对多关系。
public class IdentityDbContext: DbContext { public IdentityDbContext() : this("DefaultConnection") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { if (modelBuilder == null) { throw new ArgumentNullException("modelBuilder"); } EntityTypeConfiguration<TUser> configuration = modelBuilder.Entity<TUser>().ToTable("AspNetUsers"); configuration.HasMany<TUserRole>(u => u.Roles).WithRequired().HasForeignKey<TKey>(ur => ur.UserId); IndexAttribute indexAttribute = new IndexAttribute("UserNameIndex") { IsUnique = true }; configuration.Property((Expression<Func<TUser, string>>) (u => u.UserName)).IsRequired().HasMaxLength(0x100).HasColumnAnnotation("Index", new IndexAnnotation(indexAttribute)); configuration.Property((Expression<Func<TUser, string>>) (u => u.Email)).HasMaxLength(0x100); modelBuilder.Entity<TUserRole>().HasKey(r => new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles"); EntityTypeConfiguration<TRole> configuration2 = modelBuilder.Entity<TRole>().ToTable("AspNetRoles"); IndexAttribute attribute2 = new IndexAttribute("RoleNameIndex") { IsUnique = true }; configuration2.Property((Expression<Func<TRole, string>>) (r => r.Name)).IsRequired().HasMaxLength(0x100).HasColumnAnnotation("Index", new IndexAnnotation(attribute2)); configuration2.HasMany<TUserRole>(r => r.Users).WithRequired().HasForeignKey<TKey>(ur => ur.RoleId); }
public virtual IDbSet<TRole> Roles { get; set; }
public virtual IDbSet<TUser> Users { get; set; } } |
模仿上述设计,实现Role-Permission关系。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。