如何在Asp.net C# mvc 中缓存数据库表以防止许多数据库查询 [英] How to cache database tables to prevent many database queries in Asp.net C# mvc

查看:14
本文介绍了如何在Asp.net C# mvc 中缓存数据库表以防止许多数据库查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Asp.net mvc 4 (c#) 构建自己的 cms,我想缓存一些数据库数据,例如:本地化、搜索类别(它是长尾,每个类别都有自己的子和子子类别) 等.

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..

一直查询数据库是多余的,因为每个页面请求可能会超过 30-100 次查询,但用户很少更新这些数据库

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

那么最好的方法(性能和便利性)是什么?

我知道如何使用操作的 OutputCache,但在这种情况下它不是我需要的,它缓存 html,但我需要的是例如我自己的助手 @html.Localization("Newsletter.Tite") 将获取语言的值,或与数据等交互的任何其他帮助程序.

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.

推荐答案

您可以使用内置的 MemoryCache 用于存储您从数据库中检索到的整个结果集.

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

典型模式:

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

这篇关于如何在Asp.net C# mvc 中缓存数据库表以防止许多数据库查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆