0

I have a need to store lambda expressions in a database and execute them dynamically. The following snippet works well as is,

float result = dataRowArray.AsEnumerable().Sum(r => r.Field<float>("ColumnA") * r.Field<float>("ColumnB"));

but I'd like to store the following part in a string...

r => r.Field<float>("ColumnA") * r.Field<float>("ColumnB")

... and inject it dynamically as in:

float result = MySession.Current.dr.AsEnumerable().Sum(storedLambdaString);

I've done a ton of Googling but I'm coming up short. Any suggestions?

1

2 Answers 2

2

I suggest store the query in the database and execute using LINQ like below.

using (eEntities db = new eEntities())
{
    string query = "select name,age,salary from employees"
    var employees = db.Database.SqlQuery<Employee>(query).
}

Please note: Employee is here my custom class having properties same as queried.

Sign up to request clarification or add additional context in comments.

Comments

1

Theres a nuget package that may help you "System.Linq.Dynamic". This sample code works...

 public class TestRow
{
    public Dictionary<string,float> Field { get; set; }
    public TestRow()
    {
        this.Field = new Dictionary<string, float>();
        this.Field.Add("ColumnA", 2);
        this.Field.Add("ColumnB", 3);
    }
}
class Program
{

    static void Main(string[] args)
    {
        var testRow = new TestRow();
        string expressionString = "r.Field[\"ColumnA\"] * r.Field[\"ColumnB\"]";
        var parameter = Expression.Parameter(typeof(TestRow),"r");
        var lambdaET = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { parameter }, typeof(float), expressionString);

        var result = lambdaET.Compile().DynamicInvoke(testRow);
        Console.WriteLine(result);
        Console.ReadLine();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.