gpt4 book ai didi

c# - SQL调用的缓存结果

转载 作者:行者123 更新时间:2023-11-30 22:31:12 27 4
gpt4 key购买 nike

我有一个下拉列表,我正在使用对 SQL Server 数据库的 Entity Framework 调用的结果集进行填充。目前,该调用返回了 20 条记录,我正在考虑使用缓存。我以前从未为特定控件设置缓存,有人可以指点我一个教程吗?对于那个小数据集,这是否也有点矫枉过正?

最佳答案

如果这是 ASP.NET,那么进行缓存的最简单方法是使用 HttpContext.Current.Cache 对象。它会在您的代码中像这样工作。你可以找到more information on the Cache class on MSDN .

if (HttpContext.Current.Cache.Get("ef_results") == null)
{
var results = null; // todo: get results from EF
HttpContext.Current.Cache.Add("ef_results", // cache key
results, // cache value
null, // dependencies
System.Web.Caching.Cache.NoAbsoluteExpiration, // absolute expiration
TimeSpan.FromMinutes(30)); // sliding expiration
}

myDropDown.DataSource = HttpContext.Current.Cache.Get("ef_results");

如果这是 WPF/WinForms,那么最简单的方法就是向类中添加一个静态字段,并使用与上述相同的逻辑将 EF 查询的结果“缓存”在该静态字段中。

关于c# - SQL调用的缓存结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9363907/

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