Search code examples
asp.net-mvcdatabasecaching

How to cache data in a MVC application


I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.

In my scenario I will be using LINQ to Entities (entity framework). On the first call to GetNames (or whatever the method is) I want to grab the data from the database. I want to save the results in cache and on the second call to use the cached version if it exists.

Can anyone show an example of how this would work, where this should be implemented (model?) and if it would work.

I have seen this done in traditional ASP.NET apps , typically for very static data.


Solution

  • Reference the System.Web dll in your model and use System.Web.Caching.Cache

        public string[] GetNames()
        {
          string[] names = Cache["names"] as string[];
          if(names == null) //not in cache
          {
            names = DB.GetNames();
            Cache["names"] = names;
          }
          return names;
        }
    

    A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.