我正尝试在列表中包括每个用户的角色,如下图所示。在Index方法中,我想将用户加入该角色并将其发送到视图。但是由于某种原因,user.Roles
人们并未意识到这一点。因此,似乎缺少导航属性。我在下面添加了一个屏幕截图,以更清楚地说明我的问题。我一直在遵循一些指南,它们似乎都可以user.Roles
毫无问题地使用。
该代码对我来说似乎是正确的,在这里我缺少什么吗?
AccountController
private AppIdentityDbContext context;
public AccountController(AppIdentityDbContext _context)
{
context = _context;
}
public IActionResult Index()
{
var usersWithRoles = (from user in context.Users
select new
{
Username = user.UserName,
Email = user.Email,
RoleNames = (from userRole in user.Roles
join role in context.Roles on userRole.RoleId
equals role.Id
select role.Name).ToList()
}).ToList().Select(p => new UsersViewModel()
{
Username = p.Username,
Email = p.Email,
Role = string.Join(",", p.RoleNames)
});
return View(usersWithRoles);
}
UsersViewModel
public class UsersViewModel
{
public string Username { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}
应用用户
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
AppIdentityDbContext
public class AppIdentityDbContext : IdentityDbContext<ApplicationUser>
{
public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options)
: base(options) { }
}
AppDbContext
public class AppDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
"Server=(localdb)\\MSSQLLocalDB;Database=Local;MultipleActiveResultSets=true");
}
我得到错误:
根据您的代码,似乎您正在使用具有自定义自定义用户数据和角色的Asp.net Core Identity。
首先,请检查Startup.ConfigureServices方法,确保已将角色添加到ApplicationUser。像这样:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
//or using the following code.
//services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
// .AddRoles<IdentityRole>()
// .AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
您可以参考本文,以了解如何添加具有asp.net Core身份的角色。
然后,在控制器中,可以使用UserManager.GetRolesAsync方法获取指定用户所属的角色名称的列表。像这样的代码:
public class ApplicationUserController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context;
public ApplicationUserController(UserManager<ApplicationUser> usermanager, ApplicationDbContext context)
{
_userManager = usermanager;
_context = context;
}
public IActionResult Index()
{
var users = _userManager.Users.Select(c => new UsersViewModel()
{
Username = c.UserName,
Email = c.Email,
Role = string.Join(",", _userManager.GetRolesAsync(c).Result.ToArray())
}).ToList();
return View(users);
}
}
结果如下:
此外,在使用Asp.net标识时,数据库将使用AspNetUserRoles表存储AspNetUsers表和AspNetRoles表之间的关系(可以使用SQL Server Management Studio来检查数据库表)。如果您不想使用UserManager来获取用户的角色,则可以加入AspNetUsers,AspNetUserRoles和AspNetRoles表并查询数据库并获取所需的属性。代码如下:
public class ApplicationUserController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context;
public ApplicationUserController(UserManager<ApplicationUser> usermanager, ApplicationDbContext context)
{
_userManager = usermanager;
_context = context;
}
public IActionResult Index()
{
var result = _context.Users
.Join(_context.UserRoles, u => u.Id, ur => ur.UserId, (u, ur) => new { u, ur })
.Join(_context.Roles, ur => ur.ur.RoleId, r => r.Id, (ur, r) => new { ur, r })
.Select(c => new UsersViewModel()
{
Username = c.ur.u.UserName,
Email = c.ur.u.Email,
Role = c.r.Name
}).ToList().GroupBy(uv=> new { uv.Username, uv.Email }).Select(r=> new UsersViewModel()
{
Username = r.Key.Username,
Email = r.Key.Email,
Role = string.Join(",", r.Select(c=>c.Role).ToArray())
}).ToList();
// you could also use the following code:
var result2 = _context.Users
.Join(_context.UserRoles, u => u.Id, ur => ur.UserId, (u, ur) => new { u, ur })
.Join(_context.Roles, ur => ur.ur.RoleId, r => r.Id, (ur, r) => new { ur, r })
.ToList()
.GroupBy(uv => new { uv.ur.u.UserName, uv.ur.u.Email }).Select(r => new UsersViewModel()
{
Username = r.Key.UserName,
Email = r.Key.Email,
Role = string.Join(",", r.Select(c => c.r.Name).ToArray())
}).ToList();
return View(result);
}
}
通过使用上面的linq命令,我们也可以获得相同的结果。
额外资源:
Db上下文:
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
public class ApplicationUser: IdentityUser
{
public int Age { get; set; }
public string CustomTag { get; set; }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句