michasaucer
michasaucer

Reputation: 5226

Find User role in context.Users without Identity Managers?

I'm working on a WebApi project.

I have ApplicationUser:

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

    public string LastName { get; set; }
}

And context with his interface:

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);
    }
}

I want to find user. I'm doing it by this line of code:

var user = await this.context.Users.FindAsync(request.ApplicationUserId);

My question is, how to find Role attached to user in my context? I don't want to use UserManager or RoleManager from Identity. Is it possible to find user's roles in context?

Upvotes: 0

Views: 911

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

The only stumbling block really is that User, itself, doesn't have something like a Roles collection on it. However, you can access UserRole from the context directly and query based on the user:

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();

Yes, this requires two additional queries, but it gets the job done. The more efficient way, of course, is to just use UserManager<TUser>.GetRolesAsync.

Upvotes: 1

Related Questions