sunpengfei
2025-08-14 2b331227c0c169ac60efe25c0de8090c0c52e663
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using FlexJobApi.Core;
using Furion.DatabaseAccessor;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace FlexJobApi.UserServer.Application
{
    /// <summary>
    /// 查询角色分页列表
    /// </summary>
    /// <param name="repRole"></param>
    /// <param name="repUserInfoRole"></param>
    public class GetRolesQueryHandler(
            IRepository<Role> repRole,
            IRepository<UserRole> repUserInfoRole
        ) : IRequestHandler<GetRolesQuery, PagedListQueryResult<GetRolesQueryResultItem>>
    {
        private readonly IRepository<Role> repRole = repRole;
        private readonly IRepository<UserRole> repUserInfoRole = repUserInfoRole;
 
        /// <inheritdoc/>
        public async Task<PagedListQueryResult<GetRolesQueryResultItem>> Handle(GetRolesQuery request, CancellationToken cancellationToken)
        {
            var result = await request.PageModel.GetPagedListAsync<Role, GetRolesQueryResultItem>(
                q =>
                {
                    q = q.OrderBy(it => it.Sort).ThenBy(it => it.CreatedTime);
                    if (request.UserType.HasValue)
                    {
                        q = q.Where(it => it.UserType == request.UserType);
                    }
                    if (request.ClientType.HasValue)
                    {
                        q = q.Where(it => it.ClientType == request.ClientType);
                    }
                    if (request.Keywords.IsNotNull())
                    {
                        q = q.Where(it => it.Name.Contains(request.Keywords) || it.Remark.Contains(request.Keywords));
                    }
                    return q;
                }, cancellationToken: cancellationToken);
 
            if (result.Data.Any())
            {
                var ids = result.Data.DistinctSelect(it => it.Id);
                var userInfoRoles = await repUserInfoRole.AsQueryable().AsNoTracking()
                    .Where(it => ids.Contains(it.RoleId))
                    .Select(it => new
                    {
                        it.UserId,
                        it.RoleId
                    })
                    .ToListAsync();
                foreach (var item in result.Data)
                {
                    item.UserCount = userInfoRoles.Count(it => it.RoleId == item.Id);
                }
            }
 
            return result;
        }
    }
}