I am building an expression tree based on the conditional operator but I am unable to get the required filter working with MongoDb function.
Here is my function
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);
}
when I run the above code I received the following error
My question is how to build an expression tree using a conditional operator?
Expression<Func<TUser, bool>> filter = t => string.IsNullOrWhiteSpace(tenantId) ? t.TenantId != null : t.TenantId == tenantId;
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The problem is that the db does not support the expression you are trying to build.
Change the approach. Do not include the conditional in the expression itself
//...
Expression<Func<TUser, bool>> filter = t => t.TenantId == tenantId;
if(string.IsNullOrWhiteSpace(tenantId))
filter = t => t.TenantId != null;
//...
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
