C# 在上下文中查找用户角色。没有身份管理器的用户?

C# 在上下文中查找用户角色。没有身份管理器的用户?,c#,asp.net-core,asp.net-web-api,entity-framework-core,identity,C#,Asp.net Core,Asp.net Web Api,Entity Framework Core,Identity,我正在做一个WebApi项目 我有应用程序用户: public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } } 和context及其界面: public interface ITaskManagerDbContext { DbSet<Project> Projects { g

我正在做一个
WebApi
项目

我有
应用程序用户

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}
context
及其界面:

public interface ITaskManagerDbContext
{
    DbSet<Project> Projects { get; set; }

    DbSet<ApplicationUser> Users { get; set; }

    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}

//class

public class TaskManagerDbContext : IdentityDbContext<ApplicationUser>, ITaskManagerDbContext
{
    public TaskManagerDbContext(DbContextOptions<TaskManagerDbContext> options)
        : base(options)
    {
    }

    public DbSet<Project> Projects { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(TaskManagerDbContext).Assembly);
    }
}

我的问题是,如何在我的
上下文
中查找附加到用户的
角色
?我不想使用
Identity
中的
UserManager
rolemager
。有可能在
上下文中找到用户角色吗?

唯一的障碍是
用户本身没有类似于
角色的集合。但是,您可以直接从上下文访问
UserRole
,并根据用户进行查询:

var roleIds = await _context.UserRoles
    .Where(x => x.UserId == user.Id)
    .Select(x => x.RoleId)
    .ToListAsync();

var roles = await _context.Roles
    .Where(x => roleIds.Contains(x.Id))
    .ToListAsync();

是的,这需要两个额外的查询,但它完成了任务。当然,更有效的方法是只使用
UserManager.GetRolesAsync

愚蠢的问题,为什么不想使用为您完成所有工作的类?上下文是正常的EF上下文。据我所知,没有什么能阻止您获取具有用户角色的DbSet并自己查询它。但我不认为这样做有什么意义。
var roleIds = await _context.UserRoles
    .Where(x => x.UserId == user.Id)
    .Select(x => x.RoleId)
    .ToListAsync();

var roles = await _context.Roles
    .Where(x => roleIds.Contains(x.Id))
    .ToListAsync();