简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM