vtortola
vtortola

Reputation: 35885

Convert Expression<Func<TModel,Boolean?>> to Expression<Func<TModel,Boolean>>

A method in ASP.NET MVC is expecting an expression Expression<Func<TModel,Boolean>> (shows a checkbox HTML control on screen), but my members are Boolean?.

In our case, for this specific situation, null is the same than false, a non-checked HTML checkbox must be shown.

How may I convert from Expression<Func<TModel,Boolean?>> to Expression<Func<TModel,Boolean>> adding something like value = nullableValue.HasValue && nullableValue.Value in the way?

Just remember, than the resultant Expression must still be a MemberExpression, what makes me wonder if this is even possible.

Cheers.

Upvotes: 3

Views: 1572

Answers (1)

Maciej Jastrzebski
Maciej Jastrzebski

Reputation: 3764

In case you are acccessing a value property (like int, bool, etc) you will not get MemberExpression but rather UnaryExpression as the underlying MemberExpression is wrapped in a UnaryExpression responsible for doing Convert operation.

This seems to be resulting from the fact that value types are not reference types and do not accept a null value.

If you would accept getting UnaryExpression you can do it in a following way:

Expression<Func<TModel, Boolean?>> source = ...

var resultBody = Expression.Convert(source.Body, typeof(Boolean));    
var result = Expression.Lambda<Func<TModel, Boolean>>(resultBody, source.Parameters);

An stackoverflow question that you might find helpful.

Upvotes: 1

Related Questions