I have a drop down list box which lists roles. I want to get the list of users having that role. I mean list of users that are in \"Administrator\" role or \"CanEdit\" role.
Since bits like this tend to impact performance, I tried the other answers posted here and looked at the SQL they generated. This seems to be the most performant way of getting all the user's email addresses currently.
public void SendEmailToUsersInRole(string roleName)
{
MailMessage message = new MailMessage();
...
using (var usersDB = new ApplicationDbContext())
{
var roleId =
usersDB.Roles.First(x => x.Name == roleName).Id;
IQueryable emailQuery =
usersDB.Users.Where(x => x.Roles.Any(y => y.RoleId == roleId))
.Select(x => x.Email);
foreach (string email in emailQuery)
{
message.Bcc.Add(new MailAddress(email));
}
}
...
}
The SQL that it executes is shown below:
SELECT TOP (1)
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name]
FROM [dbo].[AspNetRoles] AS [Extent1]
WHERE N'Reviewer' = [Extent1].[Name]
SELECT
[Extent1].[Email] AS [Email]
FROM [dbo].[AspNetUsers] AS [Extent1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[AspNetUserRoles] AS [Extent2]
WHERE ([Extent1].[Id] = [Extent2].[UserId]) AND ([Extent2].[RoleId] = @p__linq__0)
)
-- p__linq__0: '3' (Type = String, Size = 4000)