我想为其中的一些键存储 nullHttpRuntime.Cache
因为我不想再次进入数据库发现没有该密钥的条目。
所以第一次,它会进入数据库并填充缓存。目的是使用缓存数据来服务以下调用,而不是执行数据库调用。
这是我正在使用的代码:
Info info = null;
if (HttpRuntime.Cache["Info_" + id.ToString() + "_" + quantity.ToString()] != null)
info = HttpRuntime.Cache["Info_" + id.ToString() + "_" + quantity.ToString()] as Info;
if (info == null)
{
info = (from dd in dc.Infos
where dd.id == id && dd.active == true && dd.quantitytooffset == quantity
select dd).SingleOrDefault();
HttpRuntime.Cache.Add("Info_" + id.ToString() + "_" + quantity.ToString(), info, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
}
最后一行代码,即 HttpRuntime.Cache.Add 抛出 System.ArgumentNullException:值不能为 null。
知道这是否可能,或者我需要使用其他数据结构来存储空值并稍后查找?
您可以使用自己的“null”值放入缓存中。
例如,
private static Info NULL_INFO = new Info();
然后你可以在 HttpRuntime.Cache.Add 中使用它而不是 null ,稍后从缓存中检索后检查你没有得到 NULL_INFO
if ( info == NULL_INFO) // if you don't have equality operator overloaded, otherwise you'd better use ReferenceEquals()
// return empty data
else if (info == null)
// proceed with try to load from database
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)