I am developing a rules engine where the rules are setup in the Database with this design:
"PropertyName" "Operator" "PropertyValue" (for e.g.: data.employee.salary = 10000). This is run against a main class that has data as a property, which in fact points to a nested class called Data and the 'data' inner class in turn has a property called employee which maps to an Employee inner class that has a property of salary which is string right now.
This is part of the RulesEngine code I have coded that uses ExpressionTrees:
// Loop through each of the rules per Ruleset and compile them against the properties of the supplied T object.
//NOTE: The values in the database column 'PropertyName' should match exactly with the properties of the T class.
rules.ForEach(rule =>
{
var genericType = Expression.Parameter(typeof(T));
// var key = MemberExpression.Property(genericType, rule.PropertyName);
var key = CreateExpression(typeof(T), rule.PropertyName); //rule.PropertyName== 'data.employee.salary'
var propertyType = GetProp(typeof(T), rule.PropertyName).PropertyType; // System.String
var value = Expression.Constant(Convert.ChangeType(rule.PropertyValue, propertyType)); //"10000"
` if (rule.Operator != ExpressionType.Lambda && rule.Operator != ExpressionType.Default) //This covers both '=' and '<>' or anything Binary-ish Operators setup in the Rules table.
{
var binaryExpression = Expression.MakeBinary(rule.Operator, key, value);
compiledExpTreeRules.Add(Expression.Lambda<Func<T, bool>>(key, genericType).Compile());
}
static LambdaExpression CreateExpression(Type type, string propertyName)
{
var param = Expression.Parameter(type, "x");
Expression body = param;
foreach (var member in propertyName.Split('.'))
{
body = Expression.PropertyOrField(body, member);
}
return Expression.Lambda(body, param);
//return MemberExpression.Property(body, propertyName);
}
The problem I am having is I am returning an Expression.Lambda from my CreateExpression() method. I had to write this method because my T input class has nested classes within and hence properties and the rules can be configured in the database, at the leaf property level of an innermost nested class.
When I try to execute this line it gives me an error:
var binaryExpression = Expression.MakeBinary(rule.Operator, key, value);
How do I make binary expression when I already know the Lambda expression, which is the 'key' parameter? That key in the MakeBinary parameter list is erroring out. I tried key.body as well but I just don't know how to either 1) Make CreateExpression() return MemberExpression.Property or 2) When it returns an lambda expression of type x=>x.innnerclass1.prop1, how can I use this as 'key' and make a BinaryExpression? I have the lambda, I have the operator (coming from the db) and I have the value but I am struggling to build a BinaryExpression out of it.
Thanks in advance!