0

I have this method for retrieving a result from my context and caching it using MemoryCache.

public IEnumerable<CustomerRole> GetCustomerRoles()
{
    string key = String.Format(CC_CACHE_CUSTOMER_ROLE_ALL, "all");
    return _cacheManager.Get(key, () =>
        {
            return from r in _customerRoleRepository.Table select r;
        }
    );
}

I then use this in my view like

@foreach (CustomerRole role in Model)
{

}

The problem I have is that because the actual result isn't executed until the data is accessed (in my view), it's not actually caching the result.

How do I force this query to run via my caching function rather than waiting until the data is used?

I've not included what _cacheManager.Get() does as I know it's caching whatever I send to it properly but if you think that is the problem, let me know and I will post the relative code.

Note: I have tried doing it this way hoping it would force the query to run but still no luck

public IEnumerable<CustomerRole> GetCustomerRoles()
{
    string key = String.Format(CC_CACHE_CUSTOMER_ROLE_ALL, "all");
    return _cacheManager.Get(key, () =>
        {
            var roles = from r in _customerRoleRepository.Table select r;
            return roles.Take(roles.Count());
        }
    );
}
Charles
  • 50,943
  • 13
  • 104
  • 142
webnoob
  • 15,747
  • 13
  • 83
  • 165

1 Answers1

2

You need to call a method like ToList() to force linq to get the data. Then just add that list to your cache.

Oscar
  • 13,594
  • 8
  • 47
  • 75
  • p.s How come `.AsEnumerable()` didn't do the same? I thought it should (as that is something I tried). – webnoob Feb 13 '14 at 17:06
  • See this: http://stackoverflow.com/questions/17968469/whats-the-differences-between-tolist-asenumerable-asqueryable – Oscar Feb 13 '14 at 17:29