【发布时间】:2017-04-27 20:17:51
【问题描述】:
我正在尝试填充一个 RoleList,其中包含每个用户的角色名称。我在查询部分遇到问题。
我有 2 个表,IdentityUserRole 表具有 UserId 和 RoleId,然后 IdentityRoles 表具有RoleId,以及角色的Name。
这是我目前所拥有的,它给我带来了多个问题。
public static IEnumerable<string> GetRolesByUserId(string userId)
{
ApplicationDbContext db = new ApplicationDbContext();
return db.Set<IdentityUserRole>().Where(r => r.UserId.Contains(userId)).Select(x => x.RoleId);
}
我最终会在此列表中调用GetRolesByUserId。
private async Task<IEnumerable<UserViewModel>> GetUserData(ApplicationDbContext db)
{
var users = db.Users;
var list = await GetUsers(db, users);
var vmlist = list.Select(item => new UserViewModel()
{
ID = item.ID,
Username = item.Username,
FirstName = item.FirstName,
LastName = item.LastName,
Email = item.Email,
TaxID = item.TaxID,
TaxIdHash = item.TaxIdHash,
IV = item.IV,
TaxIDEncrypted = item.TaxIDEncrypted,
Active = item.Active,
RoleList = GetRolesByUserId(item.ID),
Roles = "",//string.Join(",", GetRolesByUserId(item.ID)).ToArray(),
IsActive = item.IsActive,
Status = item.Status
});
UserViewModel 的 RoleList 为
public List<string> RoleList { get; set; }
我对 c# 查询相当陌生,过去 3 天一直在尝试解决这个问题。如果有人可以帮助我解决这个问题,请。谢谢你。
【问题讨论】:
-
您可以在 IdentityUserRole 表和 IdentityRoles 表之间执行
INNER JOIN。您想加入 RoleId 字段。以下是有关 LINQ 连接的一些文档:msdn.microsoft.com/en-us/library/bb311040.aspx
标签: c# sql-server linq