How to cache database tables to prevent many database queries in Asp.net C# mvc

asp.net, asp.net-mvc, asp.net-mvc-4, c#, caching

Solution

You could use the built-in `MemoryCache` to store entire resultsets you have retrieved from the database.

A typical pattern:

MyModel model = MemoryCache.Default["my_model_key"] as MyModel;
if (model == null)
{
    model = GetModelFromDatabase();
    MemoryCache.Default["my_model_key"] = model;
}

// you could use the model here

Problem

I build my own cms using Asp.net mvc 4 (c#), and I want to cache some database data, likes: localization, search categories (it's long-tail, each category have it's own sub and sub-sub categories), etc.. It's will be overkill to query the database all the time, because it can be more than 30-100 queries for each page request, however the users update those database rarely So what is the best way (performance and convenience) to do it? I know how use the OutputCache of the action, but it's not what I need in this situation , it's cache the html, but what I need is for example, that my own helper `@html.Localization("Newsletter.Tite")` will take the value of the language, or any another helper that interact with data etc. I think (not really sure) that I need to cache the data I want, only when the application is invoke for the first time, and then work with the cache location, but I don't have any experience even about to it.

Original source

Related problems