使用 linq 从 IdentityUser 列表中检索自定义配置文件数据

Retrieve custom profile data from IdentityUser list with linq

ASP.Net 具有身份的核心 3 MVC Web 应用程序

我的数据库上下文是

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
    : base(options)
    {}
etc...

因此,来自 IdentityUserContext 的用户是一个 public 虚拟 DbSet,并被实例化为

DbSet<Microsoft.AspNetCore.Identity.IdentityUser> Users

不过,我已经定义了ApplicationUser : IdentityUser来定义我自己的个人资料数据。

public class ApplicationUser : IdentityUser
{
    [Display(Name = "Is Manager")]
    public bool IsSupervisor { get; set; }
    etc....

因此,我已将 startup.cs 中的服务配置为:

services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)

我已将我的 UserManager 设置为

private readonly UserManager<ApplicationUser> _userManager

但是当我尝试使用 LINQ 根据我的自定义配置文件信息访问和过滤用户记录时(在对控制器的记录 'Detail' 调用中),我被告知这些自定义属性不可用:

        var managers = new List<SelectListItem>();
        managers.AddRange(_context.Users.Where(x => x.IsSupervisor == true).Select(manager => new SelectListItem
        {
            Text = manager.DisplayName,
            Value = manager.Id.ToString()
        }).ToList());

        ViewBag.ManagersList = managers;

/Users/robert/Projects/mvc/Vacate/Controllers/EmployeesController.cs(59,59): Error CS1061: 'IdentityUser' does not contain a definition for 'IsSupervisor' and no accessible extension method 'IsSupervisor' accepting a first argument of type 'IdentityUser' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Vacate)

那么,如果不使用单独的 table 来存储个人资料信息,有没有办法使用 LINQ 来防止用户访问您的自定义个人资料成员? 'cast' 用户是 LINQ 调用中正确的 ApplicationUser 类型?或者我在设置 ApplicationUser class 以用于 Identity 时错过了什么?

您应该使默认 ApplicationDbContext 使用新的 ApplicationUser :

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

更新您的数据库:Add-migrationUpdate-Database