Aaron Anodide
Aaron Anodide

Reputation: 17186

Which ASP.NET cache technique should I use to cache the results of a view query?

The scenario is an ASPX page with a GridView displaying data from a SqlDataSource configured to select rows from a database view that is based on a sub-optimal query (which I don't have time to fix at the current moment).

I opened up my big ASP.NET book to the 100 page chapter on caching and realized it's pretty complex, so I was just wondering if anyone can imagine this scenario and specifically tell me the technique they might use to solve the problem (besides making the query faster).

Also, the GridView has sortable columns and is contained in an UpdatePanel.

Thanks in advance.

Upvotes: 0

Views: 807

Answers (1)

scottm
scottm

Reputation: 28701

This doesn't have to be complex, it could be as simple as something like this:

public DataSet GetMyViewData()
{
    var results = HttpContext.Current.Cache["myViewResults"] as DataSet;

    if(results == null)
    {
        results = GetMyQueryResults();
        HttpContext.Current.Cache["myViewResults"] = results;
    }

    return results;
}

Of course, it depends on how large the data is, how fresh you need it, etc. etc. etc. but adding and getting from the cache is this easy.

Furthermore, if you are talking WebForms, the SqlDataSource control exposes EnableCaching and CacheDuration policies if you only need to cache the results of the Select statement. All you have to do is set the properties on the control as demonstrated below.

From MSDN:

<asp:SqlDataSource
                id="SqlDataSource1"
                runat="server"
                DataSourceMode="DataSet"
                ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
                EnableCaching="True"
                CacheDuration="20"
                SelectCommand="SELECT EmployeeID,FirstName,LastName,Title FROM Employees">
            </asp:SqlDataSource>

Upvotes: 3

Related Questions