问题描述
我正在基于条件运算符构建表达式树,但无法使用MongoDb函数使用所需的过滤器。
这是我的职能
header { color: blue; background: yellow; font-size: 20px; }
运行上面的代码时,出现以下错误
我的问题是如何使用条件运算符构建表达式树?
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;
//...