I am trying to create a dynamic formula via entity framework lambda from the columns of a model
public class OutputModel
{
public decimal Result {get;set;}
}
public class TableTest
{
public decimal A {get;set;}
public decimal B {get;set;}
public decimal C {get;set;}
}
Expression<Func<TableTest, OutputModel>> _expr = t => new OutputModel();
TestExpressionVisitor _visitor = new TestExpressionVisitor();
_visitor.Visit(_expr);
var _result = new TempDataContext().TableTests.Select(_expr);
I was thinking of using a expression visitor to modify the result
public class TestExpressionVisitor : ExpressionVisitor
{
public override Expression Visit(Expression node)
{
return base.Visit(node);
}
protected override Expression VisitMember(MemberExpression node)
{
return base.VisitMember(node);
}
}
But not really sure how to construct an Expression that can do the arithmetic function for column from a string parameter ({A}+{B}({C})) where A,B and C coming from TableTest and will put the result on OutputModel.Result. Am i on the right path to use expressionvisitor?
Any help would be appreciated.
To expand on my comment, in general you would need to:
If we use the example
(A+B)*Cthe tokens would be the objects "Bracket (open), Variable (A), Operator (+), Variable B, Bracket (Close), Operator (*), Variable (C)".I won't go into detail how to do this, because it's not part of the question, but I once wrote a very simple but powerful tokenizer using sequences of regular expressions, because these already do most of the hard work required in parsing.
Your reordered token's are now "Variable (A), Variable (B), Operator (+), Variable (C), Variable (*).
In case of a queue of tokens the last step would be:
With the token classes:
Please note I added a constructor to OutputModel, because this makes the expression much easier: