gpt4 book ai didi

c# - 如果它存在而不是数据库,我如何缓存对象并从内存中读取?

转载 作者:可可西里 更新时间:2023-11-01 08:55:48 28 4
gpt4 key购买 nike

我有以下四个类:

public class Section
{
public int SectionId { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string MetaTag { get; set; }
public string MetaDescription { get; set; }
public string UrlSafe { get; set; }
public string Header { get; set; }
public string ImageName { get; set; }
}

public interface ISectionRepository
{
List<Section> GetAllSections();
}

public class SectionRepository : ISectionRepository
{
Context context = new Context();

public List<Section> GetAllSections()
{
return context.Sections.ToList();
}
}

public class SectionApplication
{
SectionRepository sectionRepo = new SectionRepository();

public List<Section> GetAllSections()
{
return sectionRepo.GetAllSections();
}
}

在我的 Controller 中,我有

public class SectionController : Controller
{
SectionApplication sectionApp = new SectionApplication();

public ActionResult Index()
{
return View(sectionApp.GetAllSections());
}
}

现在,我想在特定时间内在内存上缓存部分,以便从缓存中读取部分(如果存在),否则从数据库中读取。

最佳答案

简单可行的方法,您可以使用MemoryCache ,代码将如下所示:

public List<Section> GetAllSections()
{
var memoryCache = MemoryCache.Default;

if (!memoryCache.Contains("section"))
{
var expiration = DateTimeOffset.UtcNow.AddMinutes(5);
var sections = context.Sections.ToList();

memoryCache.Add("section", section, expiration);
}

return memoryCache.Get("section", null);

}

关于c# - 如果它存在而不是数据库,我如何缓存对象并从内存中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999599/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com