ASP.NET Core Identity UserManager returns 不包含相关对象的用户(延迟加载)

ASP.NET Core Identity UserManager returns user without including related objects (Lazy Loading)

我有一个自定义用户 class User 来自 IdentityUser:

public class User : IdentityUser
{
    public UserInfo Info { get; set; }
}

我使用了一个 UserInfo class 和两个子 class 来根据用户类型存储额外的用户信息:

public class UserInfo 
{
    public int Id { get; set; }

    public string FirstName { get; set; }
    
    public string LastName { get; set; }
    
    public bool IsArchived { get; set; } = false;
}

public class StudentInfo : UserInfo 
{
    public List<Enrollment> Enrollments { get; set; }
}

public class InstructorInfo : UserInfo
{
   public List<Department> Departments { get; set; }
}

UsersControllerAccount() 操作中,我使用注入的 UserManager 实例从用户存储中获取用户:

public class UsersController 
{
    private readonly UserManager<User> usrMgr;
    private readonly RoleManager<IdentityRole> roleMgr;

    public UsersController(UserManager<User> usrMgr, RoleManager<IdentityRole> roleMgr) 
     => (this.usrMgr, this.roleMgr) = (usrMgr, roleMgr);

    [Authorize]
    public async Task<IActionResult> Account()
    {
        User user = await userManager.GetUserAsync(this.User); // Here user.Info is null
        return user is null ? NotFound() : View(user);
    }
}

问题是 GetUserAsync(this.User) 方法不包含 UserInfo 属性 但将其保留为 nullFindByIdAsync(userId)也不包括在内。如果这是 DbContext,我可以使用 .Include(),但我不太确定如何告诉 UserManager 在此处包含相关属性。

正如 King King, creating a custom UserManager seems to be the way to go. However, what I have ended up using is the much simpler approach mentioned by Prolog 所提到的,使用 UserManager.Users 属性 这是一个 IQueryable,因此可以在其上调用 Include() 方法:

await userManager
    .Users
    .Include(usr => usr.UserInfo)
    .FirstOrDefaultAsync(usr => usr.Id == userManager.GetUserId(this.User));