Search code examples
c#expressionexpression-treeslinq-expressions

How to ignore convert to nullable in lambda expressions?


I'm trying to build a parser of expressions to Odata, and i'm getting an error, when the field is nullable.

public class UserRight
{
    public bool? active
}

public void Test(){
    Expression<Func<UserRight, bool>> expression = p => p.Active == true;
}

It generates me the following expression:

{p => (p.Active == Convert(True, Nullable`1))}

But I'd like to receive it as

{p => (p.Active == True)}

In order to avoid this "Convert". Is there an easy way to do that? Because my parser is ready, and I would not like to rebuild it just because of a nullable field.


Solution

  • No, there's no way to avoid it. The operator you're calling accepts a bool?, not a bool, and so the argument must be a bool?, else it couldn't compile. There is an implicit conversion from bool to bool?, and that's seen from the convert expression. Without that implicit conversion it wouldn't be a valid expression.

    You could in theory manually construct your own expression that used a true nullable boolean constant value, but there's no way to make that lambda "automatically" generate such an expression, and trying to create that new expression is almost certainly way more work than simply having your query provider handle the convert expression.