4

I want to implement caching of a list pulled from the db. I've had a look at this:

How can I cache objects in ASP.NET MVC?

I have this in my code:

var addresses =  repository.GetAllAddresses();//returns IQueryable<string>

using the answer in the question above how can i cache this?, I have created the class CacheExtensions, but not sure where to go from there.

1 Answer 1

4

Once you have the extension method it's a simple matter of using it (don't forget to bring the static class you have defined the GetOrStore method into scope by adding a using directive to the namespace containing it or you won't be able to see the GetOrStore<T> extension method):

IEnumerable<string> addresses = HttpRuntime
    .Cache
    .GetOrStore<IEnumerable<string>>(
        "addresses", 
        () => repository.GetAllAddresses().ToArray()
);

Things to note:

  • We are using "addresses" as a cache key, so the result will be stored under this key.
  • We are calling .ToArray() on the IQueryable<string> in order to eagerly fetch the addresses and store the results into the cache and not the query.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.