c# - CQRS 架构模式中的查询处理程序
问题描述
我从 CQRS 开始,我想我不太确定如何(或者是否可以这样做)添加一个可以对最终查询的结果进行过滤和排序的查询。例如:
public partial class GetParticipantListQuery : IRequest<IList<ParticipantDto>>
{
public Expression<Func<ParticipantDto, bool>> Filter { get; set; } = null;
public Func<IQueryable<ParticipantDto>, IQueryable<ParticipantDto>> OrderBy { get; set; } = null;
}
然后在处理程序中将过滤和排序应用于数据库中的相应结果这是一个不错的选择吗?我怎样才能在我的查询中实现这种事情?我的目标是避免为我需要的每个过滤器创建一个查询,例如“GetParticipantsByNameQuery”、“GetParticipantsByTeamIdQuery”等等
解决方案
您可以传入一个过滤器类,其中包含过滤结果所需的属性。
例如:
public class Filter
{
//Property Name
public string Key { get; set; }
//Property Type eg. string, int, bool
public string Type { get; set; }
//Value to filter
public object Value { get; set; }
}
var result = from u in _context.Set<T>() select u;
switch(filter.Type)
{
case "string":
result = result.Where(e => EF.Property<string>(e, filter.Key).Equals((string)filter.Value));
}
这只是字符串类型的示例,您可以在 switch 块中添加自己的类型以过滤其他类型。
推荐阅读
- ios - Nativescript:错误:exportArchive:objc-metadata-generator 有冲突的配置设置
- scala - sbt 如何在 sbt 任务中获得编译结果(成功/失败)
- prometheus - 仅从最后一次抓取迭代中从普罗米修斯获取数据
- javascript - 从表格html中的一行中清除数据
- php - 找不到条带路由号码生成 API
- python - 在 Python IDLE 3.7 上制作简单的两键游戏时出错
- r - 如何使用计算值创建数据集?
- java - Gradle 找不到 tools.jar
- c# - c# 中的不可变局部值 - 一个特定用例
- typo3 - 动态元素