asp.netasp.net-identityasp.net-rolestph

Retrieving data from classes that use TPH in entityframework


So I started my project using the identity scaffolding and created an application user class that inherits from identity user

using Microsoft.AspNetCore.Identity;

namespace test6.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

       
    }
}

and some classes that inherit from this class

using Microsoft.AspNetCore.Identity;

namespace test6.Models
{
    public class Teacher : ApplicationUser
    {
        
        
        public string Course { get; set; }
        
    }
}

I have set up my roles and they seem to be working fine, however my problem is that I am trying to retrieve data from users and when retrieving data that is specific to a class that has inherited from applicationuser like Course from Teacher I get an error which is because my usermanager is initialised with ApplicationUser

private readonly UserManager<ApplicationUser> _userManager;

The method I'm using to retrieve users is this

[HttpGet]
        public async Task<IActionResult> ListTeacher()
        {
            var users = await _userManager.GetUsersInRoleAsync("Teacher");

            return View(users);
        }

So I have tried to initialise usermanager with Teacher to test but I get an error I think it's because in the dependancy I used ApplicationUser and I don't think you can use more than one. So my question is what possible solutions are there for this.(Sorry if my question isn't great or my explanation is poor)


Solution

  • Ok I think I've found a solution, turns out you can add another dependancy.

    builder.Services.AddIdentityCore<Teacher>()
        .AddRoles<IdentityRole>()
        .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<Teacher, IdentityRole>>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders()
        .AddDefaultUI();
    

    With this I can initialise usermanager with Teacher and so far it has worked.