Get list of users with assigned roles in asp.net identity 2.0

后端 未结 8 2042
你的背包
你的背包 2020-12-23 21:13

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.

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-23 21:23

    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)
    

提交回复
热议问题