Please consider this code:
System.Linq.Expressions.Expression<Func<tbl, bool>> exp_details = r => r.ID_Master == Id &&
r.Year == Year &&
r.Month == Month ;
I want to write a function that expect some argument, and then retrieve some data from my database. The problem is I want to create dynamic condition.dor example if I pass IsDeleted argument with true value I want to add r.IsDeleted == true; to exp_details. How can I do this?
The key to doing this is to use an
ExpressionVisitorwhich walks the given expression and (optionally, in a subclass) allows for replacing recognized elements with others you specify. In my case this was done for ORM (NHibernate). This is what I use: (I’ll add references to my answer later)And..
Both classes can be extended to your specific scenario. To make this relevant to the code you posted (I’m using only
IsDeletedas the parameter for simplicity):Regarding references, most of what I learned on this topic is from Marc Gravell’s “Expressions” answers [ although many other users have helped me get a grip on this 🙂 ]