我是Identity 2和C#的新手。
我想创建一个与当前所选角色的用户关联的电子邮件地址列表,由role.RoleId引用。
我做错了,我只知道......
到目前为止我已经尝试了
List<UsersEmailViewModel> EmailList = new List<UsersEmailViewModel>() { new UsersEmailViewModel { Email = ???? } }
不确定如何为角色中的每个用户创建列表条目。
也开始尝试
List<UsersEmailViewModel> EmailList = from l in UserManager.Users.Where(x => x.Roles.Any(y => y.RoleId == role.RoleId )) select new UsersEmailViewModel { Email = l.email }
但是得到一个无法转换的错误。
if (user.Roles.Count() > 0)
{
List<IdentityUserRole> userRoles = user.Roles.ToList();
foreach (var role in userRoles)
{
var dbrole = RoleManager.Roles.SingleOrDefault(x => x.Id == role.RoleId);
if ((UserManager.IsInRole(User.Identity.GetUserId(), "Admin")) || (UserManager.IsInRole(User.Identity.GetUserId(), "SuperAdmin")))
{
boundUser.Roles.Add(new RoleViewModel()
{
RoleName = dbrole.Name,
RoleId = role.RoleId,
//EmailList = Want to create list of only Email Addresses of Accounts in Role
});
}
else
{
boundUser.Roles.Add(new RoleViewModel()
{
RoleName = dbrole.Name,
RoleId = "Redacted",
EmailList = new List<UsersEmailViewModel>() { new UsersEmailViewModel { Email = "Redacted" } }
});
}
}
}
public class RoleViewModel
{
public string RoleId { get; set; }
public string RoleName { get; set; }
public List<UsersEmailViewModel> EmailList { get; set; }
}
public class UsersEmailViewModel
{
public string Email { get; set; }
}
答案 0 :(得分:1)
尝试以下方法:
List<string> list = new List<string>();
var rs = context.Roles.Where(x => x.Name == role).SingleOrDefault().Id; // where role is your role in which you want to find
var users = context.Users.Where(item => item.Roles.Any(x => x.RoleId == rs)).ToList();
foreach (var a in users)
{
list.Add(a.Email);
}