Verify the entity properties at run time from a dictionary of conditions in c#

100 Views Asked by At

I have the following requirement in my application.

My Entity Name is Payment. When making the Payment I have the following conditions. Based on these conditions I have to say it is payment or recovery or cash. I have defined all these conditions in a Dictionary.

 Dictionary<string, string> paymentTypes = new Dictionary<string, string>();
 paymentTypes.Add("Cash", "Payment.Type = 'C' and Recovery != ''");
 paymentTypes.Add("Recovery", "Payment.Recovery = ''");
 paymentTypes.Add("Payment", "Payment.Recovery != ''");

At run time how do I check the payment object values with dictionary? Based on the condition I have to pick the dictionary key.

I have tried several parses all of them or either mathematical parser they are not supporting string in the expressions.

I am not able to convert my Expressions in to dynamic expression. All these expressions will come from DB as string. How should I define the Expression when my Entity is generic? these are the expressions I made.

Expression<Func<Payment, bool>> cashFilter = payment => payment.Recovery == "" && payment.Type != "V" && payment.Type != "S"; 

            Expression<Func<Payment, bool>> paymentFilter = payment => payment.Recovery == "";

            Expression<Func<Payment, bool>> recoveryFilter = payment => payment.Recovery != ""; 
1

There are 1 best solutions below

7
John Wu On

I suggest using lambda instead of strings.

var paymentTypes = new Dictionary<string, Func<Payment,bool>>
{
    { "Cash", payment => payment.Type == 'C' && payment.Recovery != '' },
    { "Recovery", payment => payment.Recovery == '' },
    { "Payment", payment => payment.Type != 'C' && payment.Recovery != '' }
};

Then you can just evaluate it like this:

var paymentType = paymentTypes.Single( entry => entry.Value(payment) ).Key;