2

I'm building a website and I'm starting with the Domain/DAL/whatever-you-want to-call-it layer and have gone with a model/repository/service structure. I have created generic repository base class which takes care of all my CRUD functionality. I also have a generic service which for now is just a wrapper around the repository but also takes care of caching.

The problem I have is that my repository has a GetWhere method which takes a predicate that allows me to grab my entities based on certain criteria. This seemed like quite a common approach when I was doing my research. The service also takes this predicate and will then pass it through to the repository.

The problem I have is that inside the service method, I need to come up with a cache key that is based off what is being searched for in the predicate but I'm not sure how this is done or even if I can get this information at this stage.

Here is my code.

Repository method:

public IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate)
{
    return Context.Set<T>().Where(predicate);
}

Service method:

public IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate)
{
    var cacheKey = "Football." + predicate.Parameters[0].Type.Name + "." + ???;
    var result = cache.Get(cacheKey, () =>
    {
        var dbResult = repository.GetWhere(predicate);
        return dbResult;
    });
    return result;
}

So what I need is to know what to put in place of the "???" so that I can create a cache key that represents what I'm trying to retrieve so that if I call my service method something like this:

teamService.GetWhere(x => x.Name.Contains("Test"));

...I get a cache key something like "Football.Team.Name.Test" or something.

Please let me know if I am approaching this the wrong way, I feel like I might be.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Andy Furniss
  • 3,814
  • 6
  • 31
  • 56
  • This might be related: http://stackoverflow.com/questions/9746896/converting-a-lambda-expression-into-a-unique-key-for-caching – Yacoub Massad Nov 09 '15 at 19:47
  • Do you think it'd just be better to cache all of my entities in one go rather than trying to manage various different keys like this? – Andy Furniss Nov 09 '15 at 22:12

0 Answers0