3

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.

vtortola
  • 34,709
  • 29
  • 161
  • 263
  • 1
    If you just want to give your nullable Boolean a default value, use the phrase `nullableValue ?? false`. The `??` will use its value if it has one, and if not, use the value you specify. – Scott Mermelstein Mar 04 '13 at 15:32
  • Well, the app is not actually assigning values. It only uses the classes to generate HTML templates, but it is not using any instance of those classes. – vtortola Mar 04 '13 at 15:35

1 Answers1

1

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.

Community
  • 1
  • 1
Maciej Jastrzebski
  • 3,674
  • 3
  • 22
  • 28