0

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;
            }
1
  • 2
    Use OutputCacheAttribute on your controller actions. Commented Jul 14, 2015 at 3:59

1 Answer 1

2

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

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.