问题描述
我看了许多关于页面缓存和部分页面缓存的MVC应用程序的信息。不过,我想知道你会怎么缓存数据。
I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.
在我的情况,我将使用LINQ到实体(实体框架)。在第一次调用GetNames(或任何方法),我想从数据库中获取数据。我想保存在缓存中,并在第二次调用的结果,如果它存在使用缓存的版本。
In my scenario I will be using LINQ to Entities (entity framework). On the first call to GetNames (or whatever the method is) I want to grab the data from the database. I want to save the results in cache and on the second call to use the cached version if it exists.
任何人都可以显示如何做到这一点的工作,在此应实施(模式?)为例,如果它是可行的。
Can anyone show an example of how this would work, where this should be implemented (model?) and if it would work.
我已经看到了传统的ASP.NET应用这个工作,通常是非常静态数据。
I have seen this done in traditional ASP.NET apps , typically for very static data.
推荐答案
引用的DLL的System.Web在模型中,并使用的System.Web.Caching.Cache
Reference the System.Web dll in your model and use System.Web.Caching.Cache
public string[] GetNames()
{
string[] names = Cache["names"] as string[];
if(names == null) //not in cache
{
names = DB.GetNames();
Cache["names"] = names;
}
return names;
}
一个有点简单,但我想这会工作。这不是MVC具体,我一直用这个方法中缓存数据。
A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.
这篇关于如何在MVC应用程序的数据缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!