网站首页 网站源码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Dpz.Core.Infrastructure.Entity;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Dpz.Core.Infrastructure.ExpressTreeQuery;
public class BuildFilter<TEntity,TRequest>(TRequest request)
where TEntity : IBaseEntity
{
private readonly FilterDefinition<TEntity> _empty = Builders<TEntity>.Filter.Empty;
// private readonly T _request = request;
public List<FilterDefinition<TEntity>> Build()
{
var properties = GetProperties();
foreach (var item in properties) { }
// todo
return [_empty];
}
private List<PropertyInfo> GetProperties()
{
return request?
.GetType()
.GetProperties()
.Where(x => x.GetCustomAttribute<IgnorePropertyAttribute>() == null)
.ToList() ?? [];
}
private FilterDefinition<TEntity> BuildItemFilter(PropertyInfo property)
{
var queryFilters = property.GetCustomAttributes<QueryFilterAttribute>().ToList();
if (queryFilters.Count > 0)
{
// todo
return _empty;
}
var value = property.GetValue(request);
if (value == null)
{
return _empty;
}
var entityProperty = typeof(TEntity).GetProperty(property.Name);
if (entityProperty == null || entityProperty.PropertyType != property.PropertyType)
{
return _empty;
}
if (value is string strValue)
{
if (string.IsNullOrEmpty(strValue))
{
return _empty;
}
Builders<TEntity>.Filter.Regex(property.Name, new BsonRegularExpression(strValue, "i"));
}
if (value is DateTime dateTime)
{
}
return _empty;
}
}
这段代码定义了一个名为 BuildFilter<TEntity, TRequest>
的泛型类,目的是根据传入的请求对象 request
动态构建 MongoDB 的查询过滤器。以下是代码的主要功能和结构的详细解释:
泛型参数:
TEntity
: 代表 MongoDB 中的实体类型,必须实现 IBaseEntity
接口。TRequest
: 代表请求对象的类型,包含用于构建过滤器的属性。私有字段:
_empty
: 一个空的过滤器定义,使用 Builders<TEntity>.Filter.Empty
创建。Build()
方法:
GetProperties()
方法:
IgnorePropertyAttribute
特性的属性。PropertyInfo
的列表,表示可以用于构建过滤器的属性。BuildItemFilter(PropertyInfo property)
方法:
QueryFilterAttribute
特性,如果有,则可以根据该特性构建过滤器(目前尚未实现)。null
,则返回空过滤器。DateTime
类型,代码中留有待实现的逻辑。Build()
方法中,循环遍历属性并为每个属性生成过滤器的逻辑尚未实现。BuildItemFilter()
方法中,处理 QueryFilterAttribute
特性和 DateTime
类型的过滤器逻辑也尚未实现。总体来说,这段代码的目的是为 MongoDB 查询动态构建过滤器,基于请求对象的属性。它通过反射获取请求对象的属性,并根据这些属性的值生成相应的 MongoDB 过滤器。虽然目前代码尚未完成,但它为实现动态查询过滤器提供了一个良好的基础。