uthumvc
uthumvc

Reputation: 155

Getting the List of Users in a Role: ASPNEt MVC

I want to get the list of all users in role. I actually need just the Username inform of a email address: I have tried the code below but seems like I cannot access the context. I have two context in the project, One is for the Identity Sample and the other is the context I am using for my other models.

I can access the context I am using for my other data models but I cannot access that of the IdentitySample.

Any assistance will be appreciated.

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

That role.Name is not recognised as part of the fields in the roles table.

Upvotes: 0

Views: 304

Answers (3)

uthumvc
uthumvc

Reputation: 155

I was able to resolve by writing the below codes:

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);
                    }
                }

            }
           

Upvotes: 0

James Lieu
James Lieu

Reputation: 196

I think you can achieve this with the Any method

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

Let me know if this helps

Upvotes: 1

Misael Moneró
Misael Moneró

Reputation: 869

I created this method that returns a list of strings (the emails) based on a role name, hope it is useful:

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;
    }

Upvotes: 1

Related Questions