I’m trying to determine the equality of two predicates:
public T FirstOrDefault(Func<T, bool> predicate)
{
if (EntityCache.ContainsKey(predicate.GetHashCode()))
return EntityCache[predicate.GetHashCode()];
else
{
var entity = _objectSet.FirstOrDefault<T>(predicate);
EntityCache.Add(predicate.GetHashCode(), entity);
return entity;
}
}
The issue I’m having is the hash code of the predicate doesn’t account for the values used inside it, and I’m not sure how to go about retrieving them.
If for instance the predicate passed to our method above is: (r => r.Id == id) how would I go about finding the value of ‘id’ inside my FirstOrDefault method?
You’ll need to use Expression’s. They contains func’s, but they also contain the syntax tree and you can examine their ‘source code’ at runtime.