jeudi 21 novembre 2019

Converting Action to LambdaExpression

I am using NRules and trying to load rules from database.

For that, I have to use reflection to generate an Expression.

public class Product
{
     public string Attribute1 { get; }
     public List<int> Category { get; set; }   
     public void AddCategory (int category){
          this.Category.Add(category);
     }
}

using NRules.RuleModel;
using NRules.RuleModel.Builders;

var builder = new RuleBuilder();
//some logic for buildin lefthand side
Expression<Action<IContext, Product>> action = (ctx, product) => product.AddCategory(25);
builder.RightHandSide().Action(action);

My goal is to generate "Expression> action = (ctx, product) => product.AddCategory(25);" on runtime. I think the only way to do this to use reflection. Because I am reading some values from database.

I could generate the Action by using reflection:

Type actionType = typeof(Action<>).MakeGenericType(new Type[] { typeof(IContext),      
Type.GetType(actualModelName) });
MethodInfo eventMethodInfo = type.GetMethod("AddCategory");
Action actionFromReflection  = (Action)Delegate.CreateDelegate(actionType, eventMethodInfo);

But NRules method is expecting a LambdaExpression as a parameter.

How can I convert "actionFromReflection" to LambdaExpression?

LambdaExpression le = actionFromReflection  ???




Aucun commentaire:

Enregistrer un commentaire