Search code examples
c#asp.netasp.net-corelambdaexpression-trees

C# Build Expression tree based on Conditional operator to use with MongoDB filter


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

enter image description here

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;

Solution

  • 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;
        
    //...