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)
{
}
T开发者_如何学JAVAhe 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).
精彩评论