2

I work on a special project that have to convert Predicates (or Expressions) to string and store on the database and retrieve it and convert it to Predicates and evaluate it because I want to change it in run-time. Please help me to imeplement ConvertStringToPredicate and ConvertStringToPredicate methods.

public class Program
{
    static void Main(string[] args)
    {
        string predicateStr = GetPredicateFromDb(100);

        Predicate<Account> predicate = ConvertStringToPredicate(predicateStr);

        Account account = new Account();

        var status = account.Evaluate(predicate);

        //...
    }

    public static string GetPredicateFromDb(int id)
    {
        //Get Predicate String From Database
        //...
    }

    public static Predicate<Account> ConvertStringToPredicate(string predicate)
    {
        //???
    }

    public static string ConvertStringToPredicate(Predicate<Account> predicate)
    {
        //???
    }
}

public class Account
{
    public decimal Balance { get; set; }

    public bool Evaluate(Predicate<Account> matchingCriteria)
    {
        //Evaluate Predicate
        //...
    }  
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
ArMaN
  • 2,306
  • 4
  • 33
  • 55
  • 1
    This looks like the [XY](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) problem. Why are you saving a predicate as a string in your database? – Yuval Itzchakov Oct 21 '15 at 06:26
  • @YuvalItzchakov Because I want to change it in run-time – ArMaN Oct 21 '15 at 06:27
  • And why does that mean you need to persist it to the database? In what format is it stored? – Yuval Itzchakov Oct 21 '15 at 06:34
  • @YuvalItzchakov I want to save it in database as string(nvarchar) format and retrieve it in a another program and change it in run-time. – ArMaN Oct 21 '15 at 06:40
  • 1
    Check this question. It might offer insight on how to solve yours. http://stackoverflow.com/questions/821365/how-to-convert-a-string-to-its-equivalent-expression-tree – conquistador Oct 21 '15 at 06:47

1 Answers1

1

There are several libraries for expression trees serialization:

  1. metalinq
  2. expression tree serializer
  3. serialize linq
Sagi
  • 8,972
  • 3
  • 33
  • 41