怎样优雅地增删查改(五):按组织架构查询

文章目录

之前我们实现了Employee,Alarm管理模块以及通用查询应用层。

Employee的集合查询业务,是通过重写CreateFilteredQueryAsync方法,来实现按组织架构查询的过滤条件。

我们将这段逻辑代码提取到通用查询应用层中,便可实现在任何业务的按组织架构查询。

原理

查询依据

在Abp中,组织架构和用户是通过中间表AbpUserOrganizationUnits实现多对多的关系。模型如下图所示:

查询目标业务对象HealthAlarm关联了业务用户HealthClient,因业务用户与鉴权用户IdentityUser共享同一个Id,因此可以通过查询组织架构关联的User,查询到业务对象。

通过LINQ查询

EmployeeAppService中,CreateFilteredQueryAsync方法组织架构的过滤条件代码如下:

复制代码
var organizationUnitUsers = await organizationUnitAppService.GetOrganizationUnitUsersAsync(new GetOrganizationUnitUsersInput()
{
    Id = input.OrganizationUnitId.Value
});
if (organizationUnitUsers.Count() > 0)
{
    var ids = organizationUnitUsers.Select(c => c.Id);
    query = query.Where(t => ids.Contains(t.Id));
}
else
{
    query = query.Where(c => false);
}

通过反射和动态Lambda表达式查询

CreateFilteredQueryAsync是通过业务用户的IRepository获取实体的IQueryable 然后通过query.Where()实现了按组织架构的过滤条件。

IQueryable是一泛型类接口,泛型参数是实体类。要想在任意实体实现Where的过滤条件,我们使用动态拼接语言集成查询 (LINQ) 的方式实现通用查询接口,有关LINQ表达式,请阅读 LINQ 教程和有关 Lambda 表达式的文章。

实现

定义按组织架构查询过滤器(IOrganizationOrientedFilter)接口,查询实体列表Dto若实现该接口,将筛选指定 OrganizationUnitId 下的用户关联的实体。

复制代码
public interface IOrganizationOrientedFilter
{
    Guid? OrganizationUnitId { get; set; }
}

重写CreateFilteredQueryAsync方法,代码如下

复制代码
protected override async Task<IQueryable<TEntity>> CreateFilteredQueryAsync(TGetListInput input)
{
    var query = await ReadOnlyRepository.GetQueryableAsync();

    query = await ApplyOrganizationOrientedFiltered(query,input);

    return query;
}

对于OrganizationUnit服务,其依赖关系在应用层,查找指定组织架构的用户将在CurdAppServiceBase的子类实现。创建一个抽象方法GetUserIdsByOrganizationAsync

复制代码
protected abstract Task<IEnumerable<Guid>> GetUserIdsByOrganizationAsync(Guid organizationUnitId)

创建应用过滤条件方法:ApplyOrganizationOrientedFiltered,在此实现拼接LINQ表达式,代码如下:

复制代码
protected virtual async Task<IQueryable<TEntity>> ApplyOrganizationOrientedFiltered(IQueryable<TEntity> query, TGetListInput input)
{
    if (input is IOrganizationOrientedFilter && HasProperty<TEntity>("UserId"))
    {
        var property = typeof(TEntity).GetProperty("UserId");
        var filteredInput = input as IOrganizationOrientedFilter;
        if (filteredInput != null && filteredInput.OrganizationUnitId.HasValue)
        {

            var ids = await GetUserIdsByOrganizationAsync(filteredInput.OrganizationUnitId.Value);
            Expression originalExpression = null;
            var parameter = Expression.Parameter(typeof(TEntity), "p");
            foreach (var id in ids)
            {
                var keyConstantExpression = Expression.Constant(id, typeof(Guid));
                var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                var expressionSegment = Expression.Equal(propertyAccess, keyConstantExpression);

                if (originalExpression == null)
                {
                    originalExpression = expressionSegment;
                }
                else
                {
                    originalExpression = Expression.Or(originalExpression, expressionSegment);
                }
            }

            var equalExpression = originalExpression != null ?
                    Expression.Lambda<Func<TEntity, bool>>(originalExpression, parameter)
                    : p => false;

            query = query.Where(equalExpression);

        }

    }
    return query;
}

请注意,可应用过滤的条件为:

  1. input需实现IOrganizationOrientedFilter接口
  2. 实体必须包含UserId字段

否则将原封不动返回IQueryable对象。

应用

在上一章Alarm管理模块中,我们已经写好了AlarmAppService,我们需要为其实现GetUserIdsByOrganizationAsync方法。改造AlarmAppService代码如下:

复制代码
public class AlarmAppService : ExtendedCurdAppServiceBase<Matoapp.Health.Alarm.Alarm, AlarmDto, AlarmDto, AlarmBriefDto, long, GetAllAlarmInput, GetAllAlarmInput, CreateAlarmInput, UpdateAlarmInput>, IAlarmAppService
{
    private readonly IOrganizationUnitAppService organizationUnitAppService;

    public AlarmAppService(
        IOrganizationUnitAppService organizationUnitAppService,
        IRepository<Matoapp.Health.Alarm.Alarm, long> basicInventoryRepository) : base(basicInventoryRepository)
    {
        this.organizationUnitAppService = organizationUnitAppService;
    }

    protected override async Task<IEnumerable<Guid>> GetUserIdsByOrganizationAsync(Guid organizationUnitId)
    {
        var organizationUnitUsers = await organizationUnitAppService.GetOrganizationUnitUsersAsync(new GetOrganizationUnitUsersInput()
        {
            Id = organizationUnitId
        });

        var ids = organizationUnitUsers.Select(c => c.Id);
        return ids;
    }
}

在GetAllAlarmInput中实现IOrganizationOrientedFilter接口,代码如下:

复制代码
public class GetAllAlarmInput : PagedAndSortedResultRequestDto, IOrganizationOrientedFilter
{
	public Guid? OrganizationUnitId { get; set; }
    ...
}

测试

创建一些组织架构,命名"群组"

在不同"群组"下创建一些客户(Client)

在告警管理页面中,创建一些告警,并将这些告警分配给不同的客户

在客户管理中,通过选择不同的组织架构,查询当前"群组"下的客户告警


相关推荐
敲代码的 蜡笔小新3 小时前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
程序猿多布3 小时前
使用Visual Studio将C#程序发布为.exe文件
c#·visual studio
老衲有点帅5 小时前
C#多线程Thread
开发语言·c#
曼岛_6 小时前
[架构之美]linux常见故障问题解决方案(十九)
linux·运维·架构
PascalMing6 小时前
C# 通过脚本实现接口
c#·codeanalysis·接口派生
掘金-我是哪吒8 小时前
分布式微服务系统架构第131集:fastapi-python
分布式·python·微服务·系统架构·fastapi
开源架构师8 小时前
JVM 与云原生的完美融合:引领技术潮流
jvm·微服务·云原生·性能优化·serverless·内存管理·容器化
敲代码的 蜡笔小新10 小时前
【行为型之观察者模式】游戏开发实战——Unity事件驱动架构的核心实现策略
观察者模式·unity·设计模式·c#
向宇it10 小时前
【unity游戏开发——编辑器扩展】使用EditorGUI的EditorGUILayout绘制工具类在自定义编辑器窗口绘制各种UI控件
开发语言·ui·unity·c#·编辑器·游戏引擎
金刚猿12 小时前
openfeign 拦截器实现微服务上下文打通
微服务·云原生·架构