0

我是ASP.NET初學者,我試圖在ASP.NET-MVC項目中使用Identity框架構建用戶系統。Usermanager與模型繼承自應用程序用戶

我想有「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; 
} 

我也將從添加其他2繼承applicationUser,我想爲不同的用戶分別存儲不同的信息,以便在他們的數據庫文件中存儲不同的信息,並讓他們全部登錄到我的網站。

在啓動時我試圖最初使用此代碼添加管理員用戶(某處取計算器的答案):

 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("[email protected]"); 
      if (adminUser != null) 
      { 
       if (!(await userManager.IsInRoleAsync(adminUser, "ADMINISTRATOR"))) 
        await userManager.AddToRoleAsync(adminUser, "ADMINISTRATOR"); 
      } 
      else 
      { 
       var newAdmin = new applicationUser() 
       { 
        UserName = "[email protected]", 
        Email = "[email protected]", 
        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失敗。 該語句已被終止。

如果我嘗試更改「new Admin」而不是「new applicationUser」的變量Admin類型,我收到另一個異常: 找不到實體類型'Admin'。確保實體類型已被添加到模型中。

我知道這個問題是關於身份框架的基礎知識;我還沒有很好地理解他們;我剛開始明白這是原理,我不知道如何處理我的問題。

我想我需要創建新的UserManager,它將能夠操縱從基本applicationUser模型繼承的實例。如果您向我推薦有關此主題的相關資源並幫助我解決問題,我將很高興。

回答

0

如果有人會有這個問題 - 我決定不使用ApplicationUser的繼承,因爲它顯然是錯誤的方法,而是繼承IdentityUser類中的所有自定義用戶模型。爲了使這項工作我已經添加到啓動配置服務這一行:

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,而無需其他更改。