Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique string from a lambda expression

I would like to cache a EF4 result using a generic repository & memcached. This all works great, except for the fact that I need a unique key representation for a lambda expression.

For example a call to the generic repository could be:

Repository<User> userRepository = new Repository<User>();
string name = "Erik";
List<User> users_named_erik = userRepository.Find(x => x.Name == name).ToList();

In my generic repository function I need to make a unique key out of the lambda expression to store it in memcached.

So I need a function that can do this

string GetPredicate(Expression<Func<T,bool>> where)
{

}

The result of the function should be this string x=> x.Name == "Erik". And not something like +<>c__DisplayClass0) which I get from the ToString() method.

Thanks in advance.

like image 256
erikvda Avatar asked Nov 13 '22 21:11

erikvda


1 Answers

Take a look at this blog entry.

Basically, you're looking to do a "Partial Evaluation" of the expression to account for the value introduced by the closure. This MSDN Walkthrough (under the heading "Adding the Expression Evaluator") has the code that is referenced by the blog entry for incorporating the unevaluated closure members in the resulting string.

Now, it may not work with complex expressions, but it looks like it will get you on your way. Just keep in mind that it doesn't normalize expressions. That is x => x.Name == "Erik" is functionally equivalent to x => "Erik" == x.Name (and all other variants).

like image 110
Ryan Emerle Avatar answered Dec 17 '22 12:12

Ryan Emerle