Baba
Baba

Reputation: 2209

How to cache data in memory in a mvc 4 application

I am trying to implement caching in my mvc 4 application. I want to retrieve data once and not have to go back to the database back and forth. I followed the url below. My code runs well but caching is not happening

http://stevescodingblog.co.uk/net4-caching-with-mvc/

If i set a break point on the method below it never returns data from the cache. It is always going to get new data i.e vehicleData is always null.

I am new to caching. What is the best way to implement memory caching? I am using mvc 4 and visual studio 2013. Is it that Cache.set is outdated?

      public IEnumerable<Vehicle> GetVehicles()
            {
                // First, check the cache
                IEnumerable<Vehicle> vehicleData = Cache.Get("vehicles") as IEnumerable<Vehicle>;

                // If it's not in the cache, we need to read it from the repository
                if (vehicleData == null)
                {
                    // Get the repository data
                    //vehicleData = DataContext.Vehicles.OrderBy(v =&gt; v.Name).ToList();

                    vehicleData = DataContext.Vehicles.OrderBy(g=>g.Name).ToList();

                    if (vehicleData != null)
                    {
                        // Put this data into the cache for 30 minutes
                        Cache.Set("vehicles", vehicleData, 30);

                    }
                }

                return vehicleData;
            }

Upvotes: 0

Views: 1625

Answers (1)

Sanjay kumar
Sanjay kumar

Reputation: 1673

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

public string[] GetNames()
{
  string[] names = null;
  if(Cache["names"] == null)
  {
    names = DB.GetNames();
    Cache["names"] = names;
  }
  else
  {
    names = Cache["names"];
  }
  return names;
}

http://www.dotnet-tricks.com/Tutorial/mvc/4R5c050113-Understanding-Caching-in-Asp.Net-MVC-with-example.html

http://www.codeproject.com/Articles/757201/A-Beginners-Tutorial-for-Understanding-and-Imple

Upvotes: 2

Related Questions