Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I want to use an ExpressionVisitor?

I know from the MSDN's article about How to: Modify Expression Trees what an ExpressionVisitor is supposed to do. It should modify expressions.

Their example is however pretty unrealistic so I was wondering why would I need it? Could you name some real-world cases where it would make sense to modify an expression tree? Or, why does it have to be modified at all? From what to what?

It has also many overloads for visiting all kinds of expressions. How do I know when I should use any of them and what should they return? I saw people using VisitParameter and returning base.VisitParameter(node) the other on the other hand were returning Expression.Parameter(..).

like image 399
t3chb0t Avatar asked Jan 02 '17 20:01

t3chb0t


People also ask

What is ExpressionVisitor?

The ExpressionVisitor enables the visitor pattern for Expression 's.


Video Answer


1 Answers

There was a issue where on the database we had fields which contained 0 or 1 (numeric), and we wanted to use bools on the application.

The solution was to create a "Flag" object, which contained the 0 or 1 and had a conversion to bool. We used it like a bool through all the application, but when we used it in a .Where() clause the EntityFramework complained that it is unable to call the conversion method.

So we used a expression visitor to change all property accesses like .Where(x => x.Property) to .Where(x => x.Property.Value == 1) just before sending the tree to EF.

like image 177
Lucas Corsaletti Avatar answered Sep 26 '22 11:09

Lucas Corsaletti