首页 文章

具有继承自applicationUser的模型的Usermanager

提问于
浏览
0

我是ASP.NET的早期初学者,我正在尝试使用ASP.NET-MVC项目中的Identity框架构建用户系统 .

我希望“Admin”用户实体继承自我的模型中默认创建的基本实体“applicationUser”(我的小改动):

public class ApplicationUser : IdentityUser
{
    [Required]
    [StringLength(50)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    [Required]
    [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
    [Column("FirstName")]
    [Display(Name = "First Name")]
    public string FirstMidName { get; set; }

    [Display(Name = "Full Name")]
    public string FullName
    {
        get
        {
            return LastName + ", " + FirstMidName;
        }
    }
}
public class Admin: ApplicationUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AdID;
}

我还将从applicationUser中添加另外两个继承,我希望为不同的用户提供separeted模型,以便在他们的数据库文件中存储不同的信息,并让所有人登录到我的站点 .

在启动时我正在尝试使用此代码初始添加管理员用户(在stackoverflow答案中的某处):

public static async Task CreateRoles(SchoolContext context, IServiceProvider serviceProvider)
        {

            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            // First, Creating User role as each role in User Manager  
            List<IdentityRole> roles = new List<IdentityRole>();

            roles.Add(new IdentityRole { Name = "Student", NormalizedName = "STUDENT" });
            roles.Add(new IdentityRole { Name = "ADMIN", NormalizedName = "ADMINISTRATOR" });
            roles.Add(new IdentityRole { Name = "Professor", NormalizedName = "PROFESSOR" });

            //Then, the machine added Default User as the Admin user role
            foreach (var role in roles)
            {
                var roleExit = await roleManager.RoleExistsAsync(role.Name);
                if (!roleExit)
                {
                    context.Roles.Add(role);
                    context.SaveChanges();
                }
            }

            await CreateUser(context, userManager);
        }


        private static async Task CreateUser(SchoolContext context, UserManager<ApplicationUser> userManager)
        {
            var adminUser = await userManager.FindByEmailAsync("alpha@lms.com");
            if (adminUser != null)
            {
                if (!(await userManager.IsInRoleAsync(adminUser, "ADMINISTRATOR")))
                    await userManager.AddToRoleAsync(adminUser, "ADMINISTRATOR");
            }
            else
            {
                var newAdmin = new applicationUser()
                {
                    UserName = "alpha@lms.com",
                    Email = "alpha@lms.com",
                    LastName = "Admin",
                    FirstMidName = "Admin",

                };
                var result = await userManager.CreateAsync(newAdmin, "password123;");
                if (!result.Succeeded)
                {
                    var exceptionText = result.Errors.Aggregate("User Creation Failed
                     - Identity Exception. Errors were: \n\r\n\r", 
                    (current, error) => current + (" - " + error + "\n\r"));
                    throw new Exception(exceptionText);
                }
                await userManager.AddToRoleAsync(newAdmin, "ADMINISTRATOR");
            }
        }

但是当我尝试这样做时,我收到一个异常:“无法将值NULL插入列'Discriminator',表'aspnet-university;列不允许空值.INSERT失败 . 语句已被终止 . ”

如果我尝试在“新管理员”而不是“新的applicationUser”上更改变量管理员类型,我会收到另一个例外:找不到实体类型“管理员” . 确保已将实体类型添加到模型中 .

我知道这个问题是关于身份框架的基础知识;我还不太懂他们;我刚刚开始理解它的原理,我不知道如何处理我的问题 .

我猜我需要创建New UserManager,它将能够操作从基本applicationUser模型继承的实例 . 如果您向我推荐有关此主题的相关资源并帮助我解决问题,我将很高兴 .

1 回答

  • 0

    如果有人会有这个问题 - 我决定不使用ApplicationUser的继承,因为它显然是错误的方法,而是从IdentityUser类继承所有自定义用户模型 . 为了完成这项工作,我已添加到StartUp配置服务这一行:

    services.AddIdentity <IdentityUser, IdentityRole>()
                    .AddEntityFrameworkStores<YourContext>()
                    .AddDefaultTokenProviders();
    

    我的用户模型声明如下:

    public class Admin : IdentityUser
        { 
        }
    

    在上下文文件中我有这个:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<IdentityUser>(i => {
                    i.ToTable("Users");
                    i.HasKey(x => x.Id);
                });
                modelBuilder.Entity<IdentityRole<>(i => {
                    i.ToTable("Role");
                    i.HasKey(x => x.Id);
                });
    }
    

    使用此代码,我可以使用Identity的UserManager和RoleManager而无需进行其他更改 .

相关问题