Isaac Levin
Isaac Levin

Reputation: 2899

Caching result of SQL Call

I have a drop down list that I am populating with the result set of a Entity Framework call to a SQL Server database. Currently, there are 20 records returned in that call, and I am thinking of using caching. I have never setup caching for a specific control before, can someone point me to a tutorial. Is this also kind of overkill, for that small data set?

Upvotes: 2

Views: 3823

Answers (2)

Nick Ryan
Nick Ryan

Reputation: 2670

If you need to distribute the cache among a farm you could consider implementing a 2nd level cache.

EF 2nd Level Cache

Upvotes: 0

joshuapoehls
joshuapoehls

Reputation: 35237

If this is ASP.NET then the easiest way to do the caching would be to use the HttpContext.Current.Cache object. It would work something like this in your code. You can find more information on the Cache class on MSDN.

if (HttpContext.Current.Cache.Get("ef_results") == null)
{
    var results = null; // todo: get results from EF
    HttpContext.Current.Cache.Add("ef_results", // cache key
                                  results, // cache value
                                  null, // dependencies
                                  System.Web.Caching.Cache.NoAbsoluteExpiration, // absolute expiration
                                  TimeSpan.FromMinutes(30)); // sliding expiration
}

myDropDown.DataSource = HttpContext.Current.Cache.Get("ef_results");

If this is WPF/WinForms then the easiest way would be to just add a static field to your class and 'cache' the results of your EF query in that static field using the same logic as above.

Upvotes: 3

Related Questions