How to ignore convert to nullable in lambda expressions?

c# expression expression-trees linq-expressions

Question

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.

1
4
5/29/2018 5:17:46 PM

Accepted Answer

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.

4
5/29/2018 5:19:17 PM

Popular Answer

I honestly do not like Nullable in boolean attributes, more to suit your case:

Expression<Func<UserRight, bool>> expression = p => p.Active ?? false

This would consider the nulls as false, and would solve your case.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow