I have a controller action that returns the Average of a series of measurements from a group of tests. The controller basically gets the data-points from all the tests within the group specified and then returns the average of all the data points. Tests are added to the Test Group regularly.
I'd like to optimize my controller so that it caches the result (because what's the point of querying the database on every request if the data has not changed?) and rebuilds the cache only when a request is received and a new test has been added to the test group. My table structure (simplified) is below.
What's the best way to achieve this?
TEST_GROUP
------------
group_name
group_id
TEST
-------------
test_id
group_id
test_date
DATA
--------------
test_id
measurement_number
measurement
If caching for a specific period of time meets your needs you can accomplish this at the view level by doing:
[OutputCache(Duration = 300)] //Cache for 5 minutes.
public ActionResult Average() {
//Do your stuff!
}
Another option is to just cache the data you need:
HttpRuntime.Cache.Insert(key, value, null, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration);
Note in this last example the max cache will probably expire unless you have a very active application or if you configure the application pool process to not have an idle shut down.