获取角色中的用户列表:asp.net MVC



我想获得角色中所有用户的列表。我实际上只需要用户名通知的电子邮件地址:我已经尝试了下面的代码,但似乎我无法访问上下文。我在项目中有两个上下文,一个是用于身份样本,另一个是我用于其他模型的上下文。

我可以访问我正在使用的其他数据模型的上下文,但我不能访问IdentitySample的上下文。

任何帮助都将不胜感激。

ApplicationDbContext applicationDbContext = new ApplicationDbContext();

var allusers = applicationDbContext.Users.ToList();
var MDRoles = allusers.Where(x => x.Roles.Select(role => role.Name).Contains("ManagingDirector")).ToList();

这个角色。Name不能被识别为角色表中字段的一部分。

我创建了这个方法,根据角色名称返回字符串(电子邮件)列表,希望它是有用的:

public static List<string> GetUsersByRole(string NombreRole)
{
var context = new ApplicationDbContext();
List<string> correos = new List<string>();

IdentityRole rolevar1 =
context.Roles.Where(x => x.Name == NombreRole).ToList()[0];
foreach (var usuario in rolevar1.Users)
{
correos.Add(context.Users.Find(usuario.UserId).Email);
}
return correos;
}

我认为您可以使用Any方法实现这一点

var MDRoles = allusers.Where(x => 
x.Roles.Any(role => role.Name == "ManagingDirector")
).ToList();

如果有帮助请告诉我

我可以通过编写以下代码来解决:

ApplicationDbContext applicationDbContext = new ApplicationDbContext();
var CORoleID = applicationDbContext.Roles.Where(x => x.Name == "CreditOfficer").FirstOrDefault().Id;
var UsersInCORole = applicationDbContext.Users.Where(x => x.Roles.Select(role => role.RoleId).Contains(CORoleID)).ToList();
foreach (var item in UsersInCORole)
{
string body = string.Empty;
var root = AppDomain.CurrentDomain.BaseDirectory; using (var reader = new System.IO.StreamReader(root + @"/EmailTemplates/LoanApprovalStatus.htm"))
{
string readFile = reader.ReadToEnd();
string StrContent = string.Empty;
StrContent = readFile;
//Assing the field values in the template
StrContent = StrContent.Replace("[Firstname]", item.Firstname);
body = StrContent.ToString();
}
using (var message = new MailMessage(ConfigurationManager.AppSettings["mailAccount"], item.Email))
{
message.Subject = "Request For Loan Submission";
message.IsBodyHtml = true;
message.Body = body;

// Creatte the credentials:
System.Net.NetworkCredential credentials = new NetworkCredential(
ConfigurationManager.AppSettings["mailAccount"],
ConfigurationManager.AppSettings["mailPassword"]
);
using (SmtpClient client = new SmtpClient
{
EnableSsl = false,
Host = ConfigurationManager.AppSettings["mailHost"],
Port = 587,
Credentials = credentials
})
{
client.Send(message);
}
}
}

最新更新