基于条件运算符的C#构建表达式树,用于MongoDB过滤器

问题描述

我正在基于条件运算符构建表达式树,但无法使用MongoDb函数使用所需的过滤器。

这是我的职能

header { color: blue; background: yellow; font-size: 20px; }

运行上面的代码时,出现以下错误

enter image description here

我的问题是如何使用条件运算符构建表达式树?

 public Task<long> GetUserCountAsync(string tenantId,CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();

            Expression<Func<TUser,bool>> filter = t => string.IsNullOrWhiteSpace(tenantId) ? t.TenantId != null : t.TenantId == tenantId;
            return await mongoCollection.CountDocumentsAsync(filter);
        }

解决方法

问题在于数据库不支持您要构建的表达式。

更改方法。不要在表达式本身中包含条件

//...

Expression<Func<TUser,bool>> filter = t => t.TenantId == tenantId;

if(string.IsNullOrWhiteSpace(tenantId))
    filter = t => t.TenantId != null;
    
//...

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...