You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向MediatR查询传递User对象时提示无法解析符号User问题求助

问题原因

你将User属性错误定义在了GetAllInvoicesQueryHandler(查询处理者类)内部,而非GetAllInvoicesQuery(查询请求类)中。你在控制器中初始化的是请求类对象,自然无法访问到属于处理者类的User属性。

解决方案

步骤1:调整GetAllInvoicesQuery类的结构

把User属性移动到外层的请求类中,同时修改Handle方法内的引用逻辑,修改后代码如下:

public class GetAllInvoicesQuery : IRequest<IEnumerable<OrderDto>>
{
    // 把User属性移到请求类中,用来承载传入的参数
    public User User { get; set; }

    public class GetAllInvoicesQueryHandler : IRequestHandler<GetAllInvoicesQuery, IEnumerable<OrderDto>>
    {
        private readonly IEntityContext _context;
        private readonly IMapper _mapper;

        public GetAllInvoicesQueryHandler(IEntityContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<IEnumerable<OrderDto>> Handle(GetAllInvoicesQuery query, CancellationToken cancellationToken)
        {
            var invoices = await _context.Orders
                .Include(d => d.Details)
                .Include(r => r.ReservedDocument)
                .Include(b => b.Billto)
                .Include(s => s.Shipto)
                .OrderByDescending(d => d.Docdate)
                // 从传入的query参数中取User属性
                .Where(x => x.Soptype == OrderType.Invoice && x.Custnmbr == query.User.Custnmbr)
                .ProjectTo<OrderDto>(_mapper.ConfigurationProvider)
                .AsNoTracking()
                .ToListAsync(cancellationToken: cancellationToken);

            if (invoices.Count == 0)
                return null;

            return invoices.AsReadOnly();
        }
    }
}

步骤2:控制器代码无需调整

你现有控制器中new GetAllInvoicesQuery { User = (User)user }的写法已经正确,修改查询类结构后报错会自动消失。

补充说明

MediatR的标准分层逻辑为:

  • 继承IRequest的请求类:专门用来承载所有调用方传入的参数,所有需要从外部传递的参数都要定义在这个类中
  • 继承IRequestHandler的处理者类:仅用来编写对应请求的业务逻辑,不要在处理者类中定义需要外部传入的参数属性

内容的提问来源于stack exchange,提问作者Randy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:36:02