You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Identity如何获取admin或adminlower角色的用户集合

How to Filter Users by Specific Roles and Sort by DateCreated in ASP.NET Identity

Got it, let's fix this for you! The problem with your current code is that you aren't properly linking users to their assigned roles—plus, checking if the entire Roles collection contains an array doesn't work the way you think it does. Here are two reliable approaches to get the admin users you need:

ASP.NET Identity's UserManager has built-in methods to fetch users in specific roles, which avoids writing complex joins manually. Here's how to use it:

// Define the roles you want to target
var targetRoles = new string[] { "admin", "adminlower" };
var adminUsers = new List<ApplicationUser>();

// Fetch users for each role and combine them
foreach (var role in targetRoles)
{
    var usersInRole = await UserManager.GetUsersInRoleAsync(role);
    adminUsers.AddRange(usersInRole);
}

// Remove duplicates (in case a user is in both roles) and sort by DateCreated
var sortedAdminUsers = adminUsers.Distinct().OrderBy(u => u.DateCreated).ToList();

This method is great because it leverages Identity's built-in logic, so you don't have to worry about the underlying database structure.

Method 2: Direct Database Query (For Custom Scenarios)

If you prefer to write a single LINQ query directly against your DbContext, you can join users with their roles. First, get the IDs of your target roles, then filter users who have those role IDs assigned:

var targetRoles = new string[] { "admin", "adminlower" };

// First, get the IDs of the roles we care about
var roleIds = await dbContext.Roles
    .Where(r => targetRoles.Contains(r.Name))
    .Select(r => r.Id)
    .ToListAsync();

// Now filter users who have any of these role IDs, then sort
var sortedAdminUsers = await dbContext.Users
    .Where(u => u.Roles.Any(ur => roleIds.Contains(ur.RoleId)))
    .OrderBy(u => u.DateCreated)
    .ToListAsync();

Why Your Original Code Failed

  • Roles.Contains(AdminRoles) doesn't work because Contains checks if the collection has a single matching element—not an array of elements.
  • You never linked the Users collection to the Roles collection, so your query wasn't actually checking which users are in those roles.

内容的提问来源于stack exchange,提问作者niico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:29:48