gpt4 book ai didi

c# - 如何在 .core mvc 中获取用户及其角色表?

转载 作者:行者123 更新时间:2023-12-05 03:55:52 24 4
gpt4 key购买 nike

首先,我有一个来自 userManager 的用户表,我可以在其中按用户名搜索和排序。原表如下microsoft .net tutorial但现在我正在尝试从 roleManager 加入每个用户的角色。试图在 stackoverflow 中寻找其他解决方案,但我无法在下面的代码中实现它们。我应该如何修改我的代码以在一张表中从 userManager 获取用户结果并从 roleManager 获取角色?

public async Task<IActionResult> ListUsers(string sortOrder, string currentFilter, string searchString, int? pageNumber, string name)
{

ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "userid" : "username";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
var users = userManager.Users;

if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}

if (!String.IsNullOrEmpty(searchString))
{
users = userManager.Users.Where(u => u.Name.Contains(searchString));
}

switch (sortOrder)
{
case "userid":
users = users.OrderByDescending(s => s.UserName);
break;
case "username":
users = users.OrderByDescending(s => s.Name);
break;
case "Date":
users = users.OrderBy(s => s.BirthDate);
break;
case "date_desc":
users = users.OrderByDescending(s => s.BirthDate);
break;
default:
users = users.OrderBy(s => s.UserName);
break;
}
int pageSize = 50;
return View(await PaginatedList<ApplicationUser>.CreateAsync(users.AsNoTracking(), pageNumber ?? 1, pageSize));
//return View(await users.AsNoTracking().ToListAsync());
}

最佳答案

在默认的 ASP.NET Core Identity 中,User 和 Role 之间的关系是多对多的。在 EF Core 中,您应该通过为连接表包含一个实体类并映射两个单独的一对多关系来表示多对多关系。

为了获得所有用户及其相关角色,这 comment on GitHub issue似乎是 .Net Core 的当前解决方案。这是一个工作演示:

应用程序用户

public class ApplicationUser:IdentityUser<string>
{
public string Name { get; set; }
public DateTime BirthDate { get; set; }

public ICollection<ApplicationUserRole> UserRoles { get; set; }

}

应用角色

public class ApplicationRole : IdentityRole
{
public ICollection<ApplicationUserRole> UserRoles { get; set; }
}

应用程序用户角色

public class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
}

ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

builder.Entity<ApplicationUserRole>(userRole =>
{
userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId);

userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId);
});
}
}

Startup.cs

services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();

Controller

var users = _userManager.Users
.Include(u=>u.UserRoles)
.ThenInclude(ur=>ur.Role).AsNoTracking();

有关多级预先加载的 Microsoft 文档:https://learn.microsoft.com/en-us/ef/core/querying/related-data#including-multiple-levels

查看

 @foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.BirthDate)
</td>
<td>
@foreach (var userRole in item.UserRoles)
{
<p>@Html.DisplayFor(model=>userRole.Role.Name)&nbsp;</p>
}
</td>
</tr>
}

结果:

enter image description here

关于c# - 如何在 .core mvc 中获取用户及其角色表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59841178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com