How to get a unique string from a lambda expression

I would like to cache the result of EF4 using a common repository and memcached. All this works fine, except for the fact that I need a unique key representation for the lambda expression.

For example, a call to a shared repository might be:

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

In my general repository function, I need to make a unique key from a lambda expression in order 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 the string x=> x.Name == "Erik" . And not something like +<>c__DisplayClass0) that I get from the ToString() method.

Thanks in advance.

+4
source share
1 answer

Take a look at this blog post .

Basically, you want to do a “partial evaluation” of the expression to account for the value entered by the closure. This MSDN Pass (under the heading “Adding an Expression Evaluator”) contains the code referenced by the blog entry to include the unvalued close members in the resulting row.

Now it may not work with complex expressions, but it looks like it will help you. Just keep in mind that this does not normalize expressions. That is, x => x.Name == "Erik" functionally equivalent to x => "Erik" == x.Name (and all other options).

+1
source

All Articles